diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0f99fae98..ec598baa7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,9 +5,9 @@ follow the guidelines: 1. Check open [issues](https://github.com/nspcc-dev/neo-go/issues) and [pull requests](https://github.com/nspcc-dev/neo-go/pulls) for existing discussions. -1. Open an issue first, to discuss a new feature or enhancement. -1. Write tests, and make sure the test suite passes locally and on CI. -1. When optimizing something, write benchmarks and attach results: +1. Open an issue first to discuss a new feature or enhancement. +1. Write tests and make sure the test suite passes locally and on CI. +1. When optimizing something, write benchmarks and attach the results: ``` go test -run - -bench BenchmarkYourFeature -count=10 ./... >old // on master go test -run - -bench BenchmarkYourFeature -count=10 ./... >new // on your branch @@ -15,11 +15,11 @@ follow the guidelines: ``` `benchstat` is described here https://godocs.io/golang.org/x/perf/cmd/benchstat. -1. Open a pull request, and reference the relevant issue(s). +1. Open a pull request and reference the relevant issue(s). 1. Make sure your commits are logically separated and have good comments explaining the details of your change. Add a package/file prefix to your commit if that's applicable (like 'vm: fix ADD miscalculation on full moon'). -1. After receiving feedback, amend your commits or add new ones as +1. After receiving a feedback, amend your commits or add new ones as appropriate. 1. **Have fun!** diff --git a/README.md b/README.md index 291f6b70f..97375e414 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ The resulting binary is `bin/neo-go`. #### Building on Windows To build NeoGo on Windows platform we recommend you to install `make` from [MinGW -package](https://osdn.net/projects/mingw/). Then you can build NeoGo with: +package](https://osdn.net/projects/mingw/). Then, you can build NeoGo with: ``` make build @@ -77,13 +77,13 @@ is stored in a file and NeoGo allows you to store multiple files in one directory (`./config` by default) and easily switch between them using network flags. -To start Neo node on private network use: +To start Neo node on a private network, use: ``` ./bin/neo-go node ``` -Or specify a different network with appropriate flag like this: +Or specify a different network with an appropriate flag like this: ``` ./bin/neo-go node --mainnet @@ -94,12 +94,12 @@ Available network flags: - `--privnet, -p` - `--testnet, -t` -To run a consensus/committee node refer to [consensus +To run a consensus/committee node, refer to [consensus documentation](docs/consensus.md). ### Docker -By default the `CMD` is set to run a node on `privnet`, so to do this simply run: +By default, the `CMD` is set to run a node on `privnet`. So, to do this, simply run: ```bash docker run -d --name neo-go -p 20332:20332 -p 20331:20331 nspccdev/neo-go @@ -111,8 +111,7 @@ protocol) and `20331` (JSON-RPC server). ### Importing mainnet/testnet dump files If you want to jump-start your mainnet or testnet node with [chain archives -provided by NGD](https://sync.ngd.network/) follow these instructions (when -they'd be available for 3.0 networks): +provided by NGD](https://sync.ngd.network/), follow these instructions: ``` $ wget .../chain.acc.zip # chain dump file $ unzip chain.acc.zip @@ -120,7 +119,7 @@ $ ./bin/neo-go db restore -m -i chain.acc # for testnet use '-t' flag instead of ``` The process differs from the C# node in that block importing is a separate -mode, after it ends the node can be started normally. +mode. After it ends, the node can be started normally. ## Running a private network @@ -131,8 +130,8 @@ Refer to [consensus node documentation](docs/consensus.md). Please refer to [neo-go smart contract development workshop](https://github.com/nspcc-dev/neo-go-sc-wrkshp) that shows some simple contracts that can be compiled/deployed/run using neo-go compiler, SDK -and private network. For details on how Go code is translated to Neo VM -bytecode and what you can and can not do in smart contract please refer to the +and a private network. For details on how Go code is translated to Neo VM +bytecode and what you can and can not do in a smart contract, please refer to the [compiler documentation](docs/compiler.md). Refer to [examples](examples/README.md) for more NEO smart contract examples @@ -145,9 +144,9 @@ wallets. NeoGo wallet is just a [NEP-6](https://github.com/neo-project/proposals/blob/68398d28b6932b8dd2b377d5d51bca7b0442f532/nep-6.mediawiki) file that is used by CLI commands to sign various things. There is no database behind it, the blockchain is the database and CLI commands use RPC to query -data from it. At the same time it's not required to open the wallet on RPC -node to perform various actions (unless your node is providing some service -for the network like consensus or oracle nodes). +data from it. At the same time, it's not required to open a wallet on an RPC +node to perform various actions (unless your node provides some service +for the network like consensus or oracle nodes do). # Developer notes Nodes have such features as [Prometheus](https://prometheus.io/docs/guides/go-application) and @@ -167,7 +166,7 @@ where you can switch on/off and define port. Prometheus is enabled and Pprof is Feel free to contribute to this project after reading the [contributing guidelines](CONTRIBUTING.md). -Before starting to work on a certain topic, create an new issue first, +Before starting to work on a certain topic, create a new issue first describing the feature/topic you are going to implement. # Contact diff --git a/ROADMAP.md b/ROADMAP.md index bf3d33851..9d49d8983 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,7 +1,7 @@ # Roadmap for neo-go This defines approximate plan of neo-go releases and key features planned for -them. Things can change if there a need to push a bugfix or some critical +them. Things can change if there is a need to push a bugfix or some critical functionality. ## Versions 0.7X.Y (as needed) diff --git a/cli/flags/address.go b/cli/flags/address.go index 56ccf851e..f20e9948f 100644 --- a/cli/flags/address.go +++ b/cli/flags/address.go @@ -10,7 +10,7 @@ import ( "github.com/urfave/cli" ) -// Address is a wrapper for Uint160 with flag.Value methods. +// Address is a wrapper for a Uint160 with flag.Value methods. type Address struct { IsSet bool Value util.Uint160 @@ -28,12 +28,12 @@ var ( _ cli.Flag = AddressFlag{} ) -// String implements fmt.Stringer interface. +// String implements the fmt.Stringer interface. func (a Address) String() string { return address.Uint160ToString(a.Value) } -// Set implements flag.Value interface. +// Set implements the flag.Value interface. func (a *Address) Set(s string) error { addr, err := ParseAddress(s) if err != nil { @@ -44,7 +44,7 @@ func (a *Address) Set(s string) error { return nil } -// Uint160 casts address to Uint160. +// Uint160 casts an address to Uint160. func (a *Address) Uint160() (u util.Uint160) { if !a.IsSet { // It is a programmer error to call this method without @@ -82,7 +82,7 @@ func (f AddressFlag) GetName() string { return f.Name } -// Apply populates the flag given the flag set and environment +// Apply populates the flag given the flag set and environment. // Ignores errors. func (f AddressFlag) Apply(set *flag.FlagSet) { eachName(f.Name, func(name string) { @@ -90,7 +90,7 @@ func (f AddressFlag) Apply(set *flag.FlagSet) { }) } -// ParseAddress parses Uint160 form either LE string or address. +// ParseAddress parses a Uint160 from either an LE string or an address. func ParseAddress(s string) (util.Uint160, error) { const uint160size = 2 * util.Uint160Size switch len(s) { diff --git a/cli/flags/fixed8.go b/cli/flags/fixed8.go index 2f4a16d76..fcb07dea5 100644 --- a/cli/flags/fixed8.go +++ b/cli/flags/fixed8.go @@ -8,7 +8,7 @@ import ( "github.com/urfave/cli" ) -// Fixed8 is a wrapper for Uint160 with flag.Value methods. +// Fixed8 is a wrapper for a Uint160 with flag.Value methods. type Fixed8 struct { Value fixedn.Fixed8 } @@ -25,12 +25,12 @@ var ( _ cli.Flag = Fixed8Flag{} ) -// String implements fmt.Stringer interface. +// String implements the fmt.Stringer interface. func (a Fixed8) String() string { return a.Value.String() } -// Set implements flag.Value interface. +// Set implements the flag.Value interface. func (a *Fixed8) Set(s string) error { f, err := fixedn.Fixed8FromString(s) if err != nil { @@ -40,7 +40,7 @@ func (a *Fixed8) Set(s string) error { return nil } -// Fixed8 casts address to util.Fixed8. +// Fixed8 casts the address to util.Fixed8. func (a *Fixed8) Fixed8() fixedn.Fixed8 { return a.Value } @@ -61,7 +61,7 @@ func (f Fixed8Flag) GetName() string { return f.Name } -// Apply populates the flag given the flag set and environment +// Apply populates the flag given the flag set and environment. // Ignores errors. func (f Fixed8Flag) Apply(set *flag.FlagSet) { eachName(f.Name, func(name string) { @@ -69,7 +69,7 @@ func (f Fixed8Flag) Apply(set *flag.FlagSet) { }) } -// Fixed8FromContext returns parsed util.Fixed8 value provided flag name. +// Fixed8FromContext returns a parsed util.Fixed8 value provided flag name. func Fixed8FromContext(ctx *cli.Context, name string) fixedn.Fixed8 { return ctx.Generic(name).(*Fixed8).Value } diff --git a/cli/input/input.go b/cli/input/input.go index 14fac892f..8c713d55e 100644 --- a/cli/input/input.go +++ b/cli/input/input.go @@ -21,7 +21,7 @@ type ReadWriter struct { io.Writer } -// ReadLine reads line from the input without trailing '\n'. +// ReadLine reads a line from the input without trailing '\n'. func ReadLine(prompt string) (string, error) { trm := Terminal if trm == nil { @@ -46,7 +46,7 @@ func readLine(trm *term.Terminal, prompt string) (string, error) { return trm.ReadLine() } -// ReadPassword reads user password with prompt. +// ReadPassword reads the user's password with prompt. func ReadPassword(prompt string) (string, error) { trm := Terminal if trm == nil { @@ -60,7 +60,7 @@ func ReadPassword(prompt string) (string, error) { return trm.ReadPassword(prompt) } -// ConfirmTx asks for a confirmation to send tx. +// ConfirmTx asks for a confirmation to send the tx. func ConfirmTx(w io.Writer, tx *transaction.Transaction) error { fmt.Fprintf(w, "Network fee: %s\n", fixedn.Fixed8(tx.NetworkFee)) fmt.Fprintf(w, "System fee: %s\n", fixedn.Fixed8(tx.SystemFee)) diff --git a/cli/options/options.go b/cli/options/options.go index ce5534574..ae536dd2f 100644 --- a/cli/options/options.go +++ b/cli/options/options.go @@ -16,7 +16,7 @@ import ( // DefaultTimeout is the default timeout used for RPC requests. const DefaultTimeout = 10 * time.Second -// RPCEndpointFlag is a long flag name for RPC endpoint. It can be used to +// RPCEndpointFlag is a long flag name for an RPC endpoint. It can be used to // check for flag presence in the context. const RPCEndpointFlag = "rpc-endpoint" @@ -60,7 +60,7 @@ func GetNetwork(ctx *cli.Context) netmode.Magic { return net } -// GetTimeoutContext returns a context.Context with default of user-set timeout. +// GetTimeoutContext returns a context.Context with the default or a user-set timeout. func GetTimeoutContext(ctx *cli.Context) (context.Context, func()) { dur := ctx.Duration("timeout") if dur == 0 { diff --git a/cli/paramcontext/context.go b/cli/paramcontext/context.go index 1b28951a4..361af66fe 100644 --- a/cli/paramcontext/context.go +++ b/cli/paramcontext/context.go @@ -15,8 +15,8 @@ import ( // validUntilBlockIncrement is the number of extra blocks to add to an exported transaction. const validUntilBlockIncrement = 50 -// InitAndSave creates incompletely signed transaction which can used -// as input to `multisig sign`. +// InitAndSave creates an incompletely signed transaction which can be used +// as an input to `multisig sign`. func InitAndSave(net netmode.Magic, tx *transaction.Transaction, acc *wallet.Account, filename string) error { // avoid fast transaction expiration tx.ValidUntilBlock += validUntilBlockIncrement @@ -34,7 +34,7 @@ func InitAndSave(net netmode.Magic, tx *transaction.Transaction, acc *wallet.Acc return Save(scCtx, filename) } -// Read reads parameter context from file. +// Read reads the parameter context from the file. func Read(filename string) (*context.ParameterContext, error) { data, err := os.ReadFile(filename) if err != nil { @@ -48,7 +48,7 @@ func Read(filename string) (*context.ParameterContext, error) { return c, nil } -// Save writes parameter context to file. +// Save writes the parameter context to the file. func Save(c *context.ParameterContext, filename string) error { if data, err := json.Marshal(c); err != nil { return fmt.Errorf("can't marshal transaction: %w", err) diff --git a/cli/server/server.go b/cli/server/server.go index 1526b52f3..93cde7568 100644 --- a/cli/server/server.go +++ b/cli/server/server.go @@ -120,8 +120,8 @@ func newGraceContext() context.Context { return ctx } -// getConfigFromContext looks at path and mode flags in the given config and -// returns appropriate config. +// getConfigFromContext looks at the path and the mode flags in the given config and +// returns an appropriate config. func getConfigFromContext(ctx *cli.Context) (config.Config, error) { configPath := "./config" if argCp := ctx.String("config-path"); argCp != "" { @@ -131,10 +131,10 @@ func getConfigFromContext(ctx *cli.Context) (config.Config, error) { } // handleLoggingParams reads logging parameters. -// If user selected debug level -- function enables it. -// If logPath is configured -- function creates dir and file for logging. +// If a user selected debug level -- function enables it. +// If logPath is configured -- function creates a dir and a file for logging. // If logPath is configured on Windows -- function returns closer to be -// able to close sink for opened log output file. +// able to close sink for the opened log output file. func handleLoggingParams(ctx *cli.Context, cfg config.ApplicationConfiguration) (*zap.Logger, func() error, error) { level := zapcore.InfoLevel if ctx.Bool("debug") { diff --git a/cli/testdata/deploy/main.go b/cli/testdata/deploy/main.go index cd62988b6..b0b83f588 100644 --- a/cli/testdata/deploy/main.go +++ b/cli/testdata/deploy/main.go @@ -48,14 +48,14 @@ func CheckSenderWitness() { } } -// Update updates contract with the new one. +// Update updates the contract with a new one. func Update(script, manifest []byte) { ctx := storage.GetReadOnlyContext() mgmt := storage.Get(ctx, mgmtKey).(interop.Hash160) contract.Call(mgmt, "update", contract.All, script, manifest) } -// GetValue returns stored value. +// GetValue returns the stored value. func GetValue() string { ctx := storage.GetReadOnlyContext() val1 := storage.Get(ctx, key) @@ -63,7 +63,7 @@ func GetValue() string { return val1.(string) + "|" + val2.(string) } -// GetValueWithKey returns stored value with the specified key. +// GetValueWithKey returns the stored value with the specified key. func GetValueWithKey(key string) string { ctx := storage.GetReadOnlyContext() return storage.Get(ctx, key).(string) diff --git a/cli/testdata/invalid1/invalid.go b/cli/testdata/invalid1/invalid.go index 634971c15..3bdf22067 100644 --- a/cli/testdata/invalid1/invalid.go +++ b/cli/testdata/invalid1/invalid.go @@ -1,4 +1,4 @@ -// invalid is an example of contract which doesn't pass event check. +// invalid is an example of a contract which doesn't pass event check. package invalid1 import ( @@ -6,14 +6,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/interop/runtime" ) -// Notify1 emits correctly typed event. +// Notify1 emits a correctly typed event. func Notify1() bool { runtime.Notify("Event", interop.Hash160{1, 2, 3}) return true } -// Notify2 emits invalid event (ByteString instead of Hash160). +// Notify2 emits an invalid event (ByteString instead of Hash160). func Notify2() bool { runtime.Notify("Event", []byte{1, 2, 3}) diff --git a/cli/testdata/invalid2/invalid.go b/cli/testdata/invalid2/invalid.go index 3af8a53ce..07f1002cb 100644 --- a/cli/testdata/invalid2/invalid.go +++ b/cli/testdata/invalid2/invalid.go @@ -1,4 +1,4 @@ -// invalid is an example of contract which doesn't pass event check. +// invalid is an example of a contract which doesn't pass event check. package invalid2 import ( @@ -6,14 +6,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/interop/runtime" ) -// Notify1 emits correctly typed event. +// Notify1 emits a correctly typed event. func Notify1() bool { runtime.Notify("Event", interop.Hash160{1, 2, 3}) return true } -// Notify2 emits invalid event (extra parameter). +// Notify2 emits an invalid event (extra parameter). func Notify2() bool { runtime.Notify("Event", interop.Hash160{1, 2, 3}, "extra parameter") diff --git a/cli/testdata/invalid3/invalid.go b/cli/testdata/invalid3/invalid.go index ea8cd7618..2dc7c9625 100644 --- a/cli/testdata/invalid3/invalid.go +++ b/cli/testdata/invalid3/invalid.go @@ -1,4 +1,4 @@ -// invalid is an example of contract which doesn't pass event check. +// invalid is an example of a contract which doesn't pass event check. package invalid3 import ( @@ -6,14 +6,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/interop/runtime" ) -// Notify1 emits correctly typed event. +// Notify1 emits a correctly typed event. func Notify1() bool { runtime.Notify("Event", interop.Hash160{1, 2, 3}) return true } -// Notify2 emits invalid event (missing from manifest). +// Notify2 emits an invalid event (missing from manifest). func Notify2() bool { runtime.Notify("AnotherEvent", interop.Hash160{1, 2, 3}) diff --git a/cli/wallet/legacy.go b/cli/wallet/legacy.go index 38ac37fef..a50a958aa 100644 --- a/cli/wallet/legacy.go +++ b/cli/wallet/legacy.go @@ -35,8 +35,8 @@ type ( } ) -// newWalletV2FromFile reads NEO2 wallet from file. -// This should be used read-only, no operations are supported on returned wallet. +// newWalletV2FromFile reads a NEO2 wallet from the file. +// This should be used read-only, no operations are supported on the returned wallet. func newWalletV2FromFile(path string) (*walletV2, error) { file, err := os.OpenFile(path, os.O_RDWR, os.ModeAppend) if err != nil { @@ -64,7 +64,7 @@ func (a *accountV2) convert(pass string, scrypt keys.ScryptParams) (*wallet.Acco if err != nil { return nil, err } - // If it is simple signature script, newAcc does already have it. + // If it is a simple signature script, a newAcc does already have it. if len(script) != simpleSigLen { nsigs, pubs, ok := parseMultisigContract(script) if !ok { @@ -112,8 +112,8 @@ func getNumOfThingsFromInstr(script []byte) (int, int, bool) { const minMultisigLen = 37 -// parseMultisigContract accepts multisig verification script from NEO2 -// and returns list of public keys in the same order as in script.. +// parseMultisigContract accepts a multisig verification script from NEO2 +// and returns a list of public keys in the same order as in the script. func parseMultisigContract(script []byte) (int, keys.PublicKeys, bool) { // It should contain at least 1 public key. if len(script) < minMultisigLen { diff --git a/docs/cli.md b/docs/cli.md index b63b586d1..dbbbdfd91 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,10 +1,10 @@ # NeoGo CLI interface -NeoGo CLI provides all functionality from one binary, so it's used to run -node, create/compile/deploy/invoke/debug smart contracts, run vm and operate -with the wallet. The standard setup assumes that you're running a node as a -separate process, and it doesn't provide any CLI of its own, instead it just -makes RPC interface available for you. To perform any actions you invoke NeoGo +NeoGo CLI provides all functionality from one binary. It's used to run +a node, create/compile/deploy/invoke/debug smart contracts, run vm and operate +with a wallet. Standard setup assumes that you run a node as a +separate process, and it doesn't provide any CLI of its own. Instead, it just +makes RPC interface available for you. To perform any actions, you invoke NeoGo as a client that connects to this RPC node and does things you want it to do (like transferring some NEP-17 asset). @@ -40,19 +40,19 @@ detailed configuration file description. ### Starting a node -To start Neo node on private network use: +To start Neo node on private network, use: ``` ./bin/neo-go node ``` -Or specify a different network with appropriate flag like this: +Or specify a different network with an appropriate flag like this: ``` ./bin/neo-go node --mainnet ``` -By default, the node will run in foreground using current standard output for +By default, the node will run in the foreground using current standard output for logging. @@ -78,8 +78,8 @@ signal. List of the services to be restarted on SIGHUP receiving: ### DB import/exports Node operates using some database as a backend to store blockchain data. NeoGo -allows to dump chain into file from the database (when node is stopped) or to -import blocks from file into the database (also when node is stopped). Use +allows to dump chain into a file from the database (when node is stopped) or to +import blocks from a file into the database (also when node is stopped). Use `db` command for that. ## Smart contracts @@ -101,7 +101,7 @@ special `-` path can be used to read the wallet from the standard input. #### Create wallet -Use `wallet init` command to create new wallet: +Use `wallet init` command to create a new wallet: ``` ./bin/neo-go wallet init -w wallet.nep6 @@ -121,8 +121,8 @@ Use `wallet init` command to create new wallet: wallet successfully created, file location is wallet.nep6 ``` -where "wallet.nep6" is a wallet file name. This wallet will be empty, to -generate a new key pair and add an account for it use `-a` option: +where "wallet.nep6" is a wallet file name. This wallet will be empty. To +generate a new key pair and add an account for it, use `-a` option: ``` ./bin/neo-go wallet init -w wallet.nep6 -a Enter the name of the account > Name @@ -163,7 +163,7 @@ Confirm passphrase > wallet successfully created, file location is wallet.nep6 ``` -or use `wallet create` command to create new account in existing wallet: +or use `wallet create` command to create a new account in an existing wallet: ``` ./bin/neo-go wallet create -w wallet.nep6 Enter the name of the account > Joe Random @@ -182,7 +182,7 @@ just allows to reuse the old key on N3 network). ``` #### Check wallet contents -`wallet dump` can be used to see wallet contents in more user-friendly way, +`wallet dump` can be used to see wallet contents in a more user-friendly way, its output is the same NEP-6 JSON, but better formatted. You can also decrypt keys at the same time with `-d` option (you'll be prompted for password): ``` @@ -230,7 +230,7 @@ NMe64G6j6nkPZby26JAgpaCNrn1Ee4wW6E (simple signature contract): ``` #### Private key export -`wallet export` allows you to export private key in NEP-2 encrypted or WIF +`wallet export` allows you to export a private key in NEP-2 encrypted or WIF (unencrypted) form (`-d` flag). ``` $ ./bin/neo-go wallet export -w wallet.nep6 -d NMe64G6j6nkPZby26JAgpaCNrn1Ee4wW6E @@ -251,8 +251,8 @@ Confirm passphrase > #### Special accounts Multisignature accounts can be imported with `wallet import-multisig`, you'll -need all public keys and one private key to do that. Then you could sign -transactions for this multisignature account with imported key. +need all public keys and one private key to do that. Then, you could sign +transactions for this multisignature account with the imported key. `wallet import-deployed` can be used to create wallet accounts for deployed contracts. They also can have WIF keys associated with them (in case your @@ -294,8 +294,8 @@ OnChain: true BlockHash: fabcd46e93b8f4e1bc5689e3e0cc59704320494f7a0265b91ae78b4d747ee93b Success: true ``` -`OnChain` is true if transaction was included in block and `Success` is true -if it was executed successfully. +`OnChain` is true if the transaction has been included in the block; and `Success` is true +if it has been executed successfully. #### Committee members `query commitee` returns a list of current committee members: @@ -353,8 +353,8 @@ Key Votes Com ``` #### Voter data -`query voter` returns additional data about NEO holder: amount of NEO he has, -candidate he voted for (if any) and block number of the last transactions +`query voter` returns additional data about NEO holder: the amount of NEO he has, +the candidate it voted for (if any) and the block number of the last transactions involving NEO on this account: ``` $ ./bin/neo-go query voter -r http://localhost:20332 Nj91C8TxQSxW1jCE1ytFre6mg5qxTypg1Y @@ -373,7 +373,7 @@ NEP-17 commands are designed to work with any NEP-17 tokens, but NeoGo needs some metadata for these tokens to function properly. Native NEO or GAS are known to NeoGo by default, but other tokens are not. NeoGo can get this metadata from the specified RPC server, but that's an additional request to -make, so if you care about command processing delay you can import token +make. So, if you care about command processing delay, you can import token metadata into the wallet with `wallet nep17 import` command. It'll be stored in the `extra` section of the wallet. ``` @@ -391,7 +391,7 @@ Getting balance is easy: By default, you'll get data for all tokens for the default wallet's address. You can select non-default address with `-a` flag and/or select token -with `--token` flag (token hash or name can be used as parameter) +with `--token` flag (token hash or name can be used as parameter). #### Transfers @@ -405,15 +405,15 @@ parties). For example, transferring 100 GAS looks like this: You can omit `--from` parameter (default wallet's address will be used in this case), you can add `--gas` for extra network fee (raising priority of your -transaction). And you can save transaction to file with `--out` instead of +transaction). And you can save the transaction to a file with `--out` instead of sending it to the network if it needs to be signed by multiple parties. -To add optional `data` transfer parameter specify `data` positional argument +To add optional `data` transfer parameter, specify `data` positional argument after all required flags. Refer to `wallet nep17 transfer --help` command description for details. -One `transfer` invocation creates one transaction, but in case you need to do -many transfers you can save on network fees by doing multiple token moves with +One `transfer` invocation creates one transaction. In case you need to do +many transfers, you can save on network fees by doing multiple token moves with one transaction by using `wallet nep17 multitransfer` command. It can transfer things from one account to many, its syntax differs from `transfer` in that you don't have `--token`, `--to` and `--amount` options, but instead you can @@ -426,7 +426,7 @@ transfer as above can be done with `multitransfer` by doing this: #### GAS claims While Neo N3 doesn't have any notion of "claim transaction" and has GAS -automatically distributed with every NEO transfer for NEO owners you still +automatically distributed with every NEO transfer for NEO owners, you still won't get GAS if you don't do any actions. So the old `wallet claim` command was updated to be an easier way to do NEO "flipping" when you send a transaction that transfers all of your NEO to yourself thereby triggering GAS @@ -451,7 +451,7 @@ By default, no token ID specified, i.e. common `balanceOf` method is called. #### Transfers -Specify token ID via `--id` flag to transfer NEP-11 token. Specify amount to +Specify token ID via `--id` flag to transfer NEP-11 token. Specify the amount to transfer divisible NEP-11 token: ``` @@ -462,7 +462,7 @@ By default, no amount is specified, i.e. the whole token is transferred for non-divisible tokens and 100% of the token is transferred if there is only one owner of this token for divisible tokens. -Unlike NEP-17 tokens functionality, `multitransfer` command currently not +Unlike NEP-17 tokens functionality, `multitransfer` command is currently not supported on NEP-11 tokens. #### Tokens Of @@ -536,7 +536,7 @@ Some basic commands available there: - `ops` -- show the opcodes of currently loaded contract - `run` -- executes currently loaded contract -Use `help` command to get more detailed information on all possibilities and +Use `help` command to get more detailed information on all options and particular commands. Note that this VM is completely disconnected from the blockchain, so you won't have all interop functionality available for smart contracts (use test invocations via RPC for that). diff --git a/docs/compiler.md b/docs/compiler.md index 9c60bb7ee..bd9375cdd 100644 --- a/docs/compiler.md +++ b/docs/compiler.md @@ -1,26 +1,26 @@ # NeoGo smart contract compiler -The neo-go compiler compiles Go programs to bytecode that the NEO virtual machine can understand. +The neo-go compiler compiles Go programs to a bytecode that the NEO virtual machine can understand. ## Language compatibility -The compiler is mostly compatible with regular Go language specification, but +The compiler is mostly compatible with regular Go language specification. However, there are some important deviations that you need to be aware of that make it a dialect of Go rather than a complete port of the language: * `new()` is not supported, most of the time you can substitute structs with composite literals * `make()` is supported for maps and slices with elements of basic types - * `copy()` is supported only for byte slices, because of underlying `MEMCPY` opcode + * `copy()` is supported only for byte slices because of the underlying `MEMCPY` opcode * pointers are supported only for struct literals, one can't take an address of an arbitrary variable * there is no real distinction between different integer types, all of them - work as big.Int in Go with a limit of 256 bit in width, so you can use + work as big.Int in Go with a limit of 256 bit in width; so you can use `int` for just about anything. This is the way integers work in Neo VM and adding proper Go types emulation is considered to be too costly. * goroutines, channels and garbage collection are not supported and will never be because emulating that aspects of Go runtime on top of Neo VM is close to impossible - * `defer` and `recover` are supported except for cases where panic occurs in - `return` statement, because this complicates implementation and imposes runtime + * `defer` and `recover` are supported except for the cases where panic occurs in + `return` statement because this complicates implementation and imposes runtime overhead for all contracts. This can easily be mitigated by first storing values in variables and returning the result. * lambdas are supported, but closures are not. @@ -53,8 +53,8 @@ this requires you to set proper `GOROOT` environment variable, like export GOROOT=/usr/lib64/go/1.15 ``` -The best way to create a new contract is using `contract init` command. This will -create an example source file, config file and `go.mod` with `github.com/nspcc-dev/neo-go/pkg/interop` dependency. +The best way to create a new contract is to use `contract init` command. This will +create an example source file, a config file and `go.mod` with `github.com/nspcc-dev/neo-go/pkg/interop` dependency. ``` $ ./bin/neo-go contract init --name MyAwesomeContract $ cd MyAwesomeContract @@ -73,8 +73,8 @@ $ go mod tidy ``` By default, the filename will be the name of your .go file with the .nef -extension, the file will be located in the same directory where your Go contract -is. If you want another location for your compiled contract: +extension, the file will be located in the same directory with your Go contract. +If you want another location for your compiled contract: ``` ./bin/neo-go contract compile -i contract.go --out /Users/foo/bar/contract.nef @@ -207,14 +207,14 @@ other supported language. ### Deploying Deploying a contract to blockchain with neo-go requires both NEF and JSON -manifest generated by the compiler from configuration file provided in YAML -format. To create contract manifest pass YAML file with `-c` parameter and -specify manifest output file with `-m`: +manifest generated by the compiler from a configuration file provided in YAML +format. To create contract manifest, pass a YAML file with `-c` parameter and +specify the manifest output file with `-m`: ``` ./bin/neo-go contract compile -i contract.go -c config.yml -m contract.manifest.json ``` -Example YAML file contents: +Example of such YAML file contents: ``` name: Contract safemethods: [] @@ -226,14 +226,14 @@ events: type: String ``` -Then the manifest can be passed to the `deploy` command via `-m` option: +Then, the manifest can be passed to the `deploy` command via `-m` option: ``` $ ./bin/neo-go contract deploy -i contract.nef -m contract.manifest.json -r http://localhost:20331 -w wallet.json ``` Deployment works via an RPC server, an address of which is passed via `-r` -option and should be signed using a wallet from `-w` option. More details can +option, and should be signed using a wallet from `-w` option. More details can be found in `deploy` command help. #### Config file @@ -271,7 +271,7 @@ anything else | `Any` `interop.*` types are defined as aliases in `github.com/nspcc-dev/neo-go/pkg/interop` module with the sole purpose of correct manifest generation. -As an example consider `Transfer` event from `NEP-17` standard: +As an example, consider `Transfer` event from `NEP-17` standard: ``` - name: Transfer parameters: @@ -285,14 +285,14 @@ As an example consider `Transfer` event from `NEP-17` standard: By default, compiler performs some sanity checks. Most of the time it will report missing events and/or parameter type mismatch. -Using variable as an event name in code isn't prohibited but will prevent -compiler from analyzing an event. It is better to use either constant or string literal. +It isn't prohibited to use a variable as an event name in code, but it will prevent +the compiler from analyzing the event. It is better to use either constant or string literal. The check can be disabled with `--no-events` flag. ##### Permissions Each permission specifies contracts and methods allowed for this permission. -If contract is not specified in a rule, specified set of methods can be called on any contract. -By default, no calls are allowed. Simplest permission is to allow everything: +If a contract is not specified in a rule, specified set of methods can be called on any contract. +By default, no calls are allowed. The simplest permission is to allow everything: ``` - methods: '*' ``` @@ -303,10 +303,10 @@ for most of the NEP-17 token implementations: - methods: ["onNEP17Payment"] ``` -In addition to `methods` permission can have one of these fields: -1. `hash` contains hash and restricts set of contracts to a single contract. -2. `group` contains public key and restricts set of contracts to those who -have corresponding group in their manifest. +In addition to `methods`, permission can have one of these fields: +1. `hash` contains hash and restricts a set of contracts to a single contract. +2. `group` contains public key and restricts a set of contracts to those that +have the corresponding group in their manifest. Consider an example: ``` @@ -322,32 +322,32 @@ This set of permissions allows calling: - `start` and `stop` methods of contract with hash `fffdc93764dbaddd97c48f252a53ea4643faa3fd` - `update` method of contract in group with public key `03184b018d6b2bc093e535519732b3fd3f7551c8cffaf4621dd5a0b89482ca66c9` -Also note, that native contract must be included here too. For example, if your contract +Also note that a native contract must be included here too. For example, if your contract transfers NEO/GAS or gets some info from the `Ledger` contract, all of these calls must be allowed in permissions. -Compiler does its best to ensure correct permissions are specified in config. +The compiler does its best to ensure that correct permissions are specified in the config. Incorrect permissions will result in runtime invocation failures. -Using either constant or literal for contract hash and method will allow compiler +Using either constant or literal for contract hash and method will allow the compiler to perform more extensive analysis. This check can be disabled with `--no-permissions` flag. ##### Overloads NeoVM allows a contract to have multiple methods with the same name -but different parameters number. Go lacks this feature but this can be circumvented -with `overloads` section. Essentially it is a mapping from default contract method names +but different parameters number. Go lacks this feature, but this can be circumvented +with `overloads` section. Essentially, it is a mapping from default contract method names to the new ones. ``` - overloads: oldName1: newName oldName2: newName ``` -Because the use-case for this is to provide multiple implementations with the same ABI name, +Since the use-case for this is to provide multiple implementations with the same ABI name, `newName` is required to be already present in the compiled contract. -As an example consider [`NEP-11` standard](https://github.com/neo-project/proposals/blob/master/nep-11.mediawiki#transfer). -It requires divisible NFT contract to have 2 `transfer` methods. To achieve this we might implement -`Tranfer` and `TransferDivisible` and specify emitted name in config: +As an example, consider [`NEP-11` standard](https://github.com/neo-project/proposals/blob/master/nep-11.mediawiki#transfer). +It requires a divisible NFT contract to have 2 `transfer` methods. To achieve this, we might implement +`Transfer` and `TransferDivisible` and specify the emitted name in the config: ``` - overloads: transferDivisible:transfer @@ -361,15 +361,15 @@ This is achieved with `manifest add-group` command. ./bin/neo-go contract manifest add-group -n contract.nef -m contract.manifest.json --sender --wallet /path/to/wallet.json --account ``` It accepts contract `.nef` and manifest files emitted by `compile` command as well as -sender and signer accounts. `--sender` is the account who will send deploy transaction later (not necessarily in wallet). +sender and signer accounts. `--sender` is the account that will send deploy transaction later (not necessarily in wallet). `--account` is the wallet account which signs contract hash using group private key. #### Neo Express support It's possible to deploy contracts written in Go using [Neo -Express](https://github.com/neo-project/neo-express) which is a part of [Neo +Express](https://github.com/neo-project/neo-express), which is a part of [Neo Blockchain -Toolkit](https://github.com/neo-project/neo-blockchain-toolkit/). To do that +Toolkit](https://github.com/neo-project/neo-blockchain-toolkit/). To do that, you need to generate a different metadata file using YAML written for deployment with neo-go. It's done in the same step with compilation via `--config` input parameter and `--abi` output parameter, combined with debug @@ -380,11 +380,11 @@ $ ./bin/neo-go contract compile -i contract.go --config contract.yml -o contract ``` This file can then be used by toolkit to deploy contract the same way -contracts in other languagues are deployed. +contracts in other languages are deployed. ### Invoking -You can import your contract into the standalone VM and run it there (see [VM +You can import your contract into a standalone VM and run it there (see [VM documentation](vm.md) for more info), but that only works for simple contracts that don't use blockchain a lot. For more real contracts you need to deploy them first and then do test invocations and regular invocations with `contract diff --git a/docs/consensus.md b/docs/consensus.md index 9f16acd79..7b3cc20ee 100644 --- a/docs/consensus.md +++ b/docs/consensus.md @@ -1,14 +1,14 @@ # NeoGo consensus node -NeoGo node can act as a consensus node. A consensus node differs from regular +NeoGo node can act as a consensus node. A consensus node differs from a regular one in that it participates in block acceptance process using dBFT -protocol. Any committee node can also be elected as CN therefore they're +protocol. Any committee node can also be elected as a CN; therefore, they're expected to follow the same setup process as CNs (to be ready to become CNs if/when they're elected). -While regular nodes on Neo network don't need any special keys CNs always have -one used to sign dBFT messages and blocks. So the main difference between -regular node and consensus/committee node is that it should be configured to +While regular nodes on Neo network don't need any special keys, CNs always have +one used to sign dBFT messages and blocks. So, the main difference between +a regular node and a consensus/committee node is that it should be configured to use some key from some wallet. ## Running a CN on public networks @@ -27,7 +27,7 @@ be enough for the first year of blockchain). NeoGo is a single binary that can be run on any modern GNU/Linux distribution. We recommend using major well-supported OSes like CentOS, Debian -or Ubuntu, make sure they're updated with the latest security patches. +or Ubuntu. Make sure they're updated with the latest security patches. No additional packages are needed for NeoGo CN. @@ -38,9 +38,9 @@ Github](https://github.com/nspcc-dev/neo-go/releases) or use [Docker image](https://hub.docker.com/r/nspccdev/neo-go). It has everything included, no additional plugins needed. -Take appropriate (mainnet/testnet) configuration [from the +Take an appropriate (mainnet/testnet) configuration [from the repository](https://github.com/nspcc-dev/neo-go/tree/master/config) and save -in some directory (we'll assume that it's available in the same directory as +it in some directory (we'll assume that it's available in the same directory as neo-go binary). ### Configuration and execution @@ -59,24 +59,24 @@ is a password to your CN key. Run the node in a regular way after that: $ neo-go node --mainnet --config-path ./ ``` where `--mainnet` is your network (can be `--testnet` for testnet) and -`--config-path` is a path to configuration file directory. If the node starts -fine it'll be logging events like synchronized blocks. The node doesn't have +`--config-path` is a path to the configuration file directory. If the node starts +fine, it'll be logging events like synchronized blocks. The node doesn't have any interactive CLI, it only outputs logs so you can wrap this command in a systemd service file to run automatically on system startup. -Notice that the default configuration has RPC and Prometheus services enabled, -you can turn them off for security purposes or restrict access to them with a -firewall. Carefuly review all other configuration options to see if they meet +Notice that the default configuration has RPC and Prometheus services enabled. +You can turn them off for security purposes or restrict access to them with a +firewall. Carefully review all other configuration options to see if they meet your expectations. Details on various configuration options are provided in the [node configuration documentation](node-configuration.md), CLI commands are provided in the [CLI documentation](cli.md). ### Registration -To register as a candidate use neo-go as CLI command with an external RPC +To register as a candidate, use neo-go as CLI command with an external RPC server for it to connect to (for chain data and transaction submission). You can use any public RPC server or an RPC server of your own like the node -started at previous step. We'll assume that you're running the next command on +started at the previous step. We'll assume that you run the next command on the same node in default configuration with RPC interface available at port 10332. @@ -91,15 +91,15 @@ path to NEP-6 wallet file and `http://localhost:10332` is an RPC node to use. This command will create and send appropriate transaction to the network and -you should then wait for it to settle in a block. If all goes well it'll end +you should then wait for it to settle in a block. If all goes well, it'll end with "HALT" state and your registration will be completed. You can use `query tx` command to see transaction status or `query candidates` to see if -your candidate was added. +your candidate has been added. ### Voting -After registration completion if you own some NEO you can also vote for your -candidate to help it become CN and receive additional voter GAS. To do that +After registration is completed, if you own some NEO, you can also vote for your +candidate to help it become a CN and receive additional voter GAS. To do that, you need to know the public key of your candidate, which can either be seen in `query candidates` command output or extracted from wallet `wallet dump-keys` command: @@ -117,10 +117,10 @@ use: $ neo-go wallet candidate vote -a NiKEkwz6i9q6gqfCizztDoHQh9r9BtdCNa -w wallet.json -r http://localhost:10332 -c 0363f6678ea4c59e292175c67e2b75c9ba7bb73e47cd97cdf5abaf45de157133f5 ``` -where `NiKEkwz6i9q6gqfCizztDoHQh9r9BtdCNa` is voter's address, `wallet.json` -is NEP-6 wallet file path, `http://localhost:10332` is RPC node address and -`0363f6678ea4c59e292175c67e2b75c9ba7bb73e47cd97cdf5abaf45de157133f5` is a -public key voter votes for. This command also returns transaction hash and you +where `NiKEkwz6i9q6gqfCizztDoHQh9r9BtdCNa` is the voter's address, `wallet.json` +is the NEP-6 wallet file path, `http://localhost:10332` is the RPC node address and +`0363f6678ea4c59e292175c67e2b75c9ba7bb73e47cd97cdf5abaf45de157133f5` is the +public key the voter votes for. This command also returns transaction hash and you need to wait for this transaction to be accepted into one of subsequent blocks. ## Private NeoGo network @@ -135,11 +135,11 @@ Four-node setup uses ports 20333-20336 for P2P communication and ports 20001-20004). Single-node is on ports 20333/30333/20001 for P2P/RPC/Prometheus. -NeoGo default privnet configuration is made to work with four node consensus, +NeoGo default privnet configuration is made to work with four-node consensus, you have to modify it if you're to use single consensus node. Node wallets are located in the `.docker/wallets` directory where -`wallet1_solo.json` is used for single-node setup and all the other ones for +`wallet1_solo.json` is used for single-node setup and all others for four-node setup. #### Prerequisites @@ -148,7 +148,7 @@ four-node setup. - `go` compiler #### Instructions -You can use existing docker-compose file located in `.docker/docker-compose.yml`: +You can use an existing docker-compose file located in `.docker/docker-compose.yml`: ```bash make env_image # build image make env_up # start containers, use "make env_single" for single CN @@ -170,12 +170,12 @@ make env_clean ### Start nodes manually 1. Create a separate config directory for every node and -place corresponding config named `protocol.privnet.yml` there. +place the corresponding config named `protocol.privnet.yml` there. 2. Edit configuration file for every node. Examples can be found at `config/protocol.privnet.docker.one.yml` (`two`, `three` etc.). 1. Add `UnlockWallet` section with `Path` and `Password` strings for NEP-6 - wallet path and password for the account to be used for consensus node. + wallet path and the password for the account to be used for the consensus node. 2. Make sure that your `MinPeers` setting is equal to the number of nodes participating in consensus. This requirement is needed for nodes to correctly diff --git a/docs/conventions.md b/docs/conventions.md index 493d95371..cfd1819bb 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -1,9 +1,9 @@ # Conventions This document will list conventions that this repo should follow. These are -guidelines and if you believe that one should not be followed, then please state +the guidelines, and if you believe that one should not be followed, please state why in your PR. If you believe that a piece of code does not follow one of the -conventions listed, then please open an issue before making any changes. +conventions listed, please open an issue before making any changes. When submitting a new convention, please open an issue for discussion, if possible please highlight parts in the code where this convention could help the diff --git a/docs/node-configuration.md b/docs/node-configuration.md index d8f2dc506..638964572 100644 --- a/docs/node-configuration.md +++ b/docs/node-configuration.md @@ -1,7 +1,7 @@ # NeoGo node configuration file This section contains detailed NeoGo node configuration file description -including default config values and tips to set up configurable values. +including default config values and some tips to set up configurable values. Each config file contains two sections. `ApplicationConfiguration` describes node-related settings and `ProtocolConfiguration` contains protocol-related settings. See the @@ -17,14 +17,14 @@ node-related settings described in the table below. | Section | Type | Default value | Description | | --- | --- | --- | --- | | Address | `string` | `127.0.0.1` | Node address that P2P protocol handler binds to. | -| AnnouncedPort | `uint16` | Same as the `NodePort` | Node port which should be used to announce node's port on P2P layer, can differ from `NodePort` node is bound to (for example, if your node is behind NAT). | -| AttemptConnPeers | `int` | `20` | Number of connection to try to establish when the connection count drops below the `MinPeers` value.| +| AnnouncedPort | `uint16` | Same as `NodePort` | Node port which should be used to announce node's port on P2P layer, it can differ from the `NodePort` the node is bound to (for example, if your node is behind NAT). | +| AttemptConnPeers | `int` | `20` | Number of connection to try to establish when the connection count drops below the `MinPeers` value.| | DBConfiguration | [DB Configuration](#DB-Configuration) | | Describes configuration for database. See the [DB Configuration](#DB-Configuration) section for details. | | DialTimeout | `int64` | `0` | Maximum duration a single dial may take in seconds. | | ExtensiblePoolSize | `int` | `20` | Maximum amount of the extensible payloads from a single sender stored in a local pool. | | LogPath | `string` | "", so only console logging | File path where to store node logs. | | MaxPeers | `int` | `100` | Maximum numbers of peers that can be connected to the server. | -| MinPeers | `int` | `5` | Minimum number of peers for normal operation, when the node has less than this number of peers it tries to connect with some new ones. | +| MinPeers | `int` | `5` | Minimum number of peers for normal operation; when the node has less than this number of peers it tries to connect with some new ones. | | NodePort | `uint16` | `0`, which is any free port | The actual node port it is bound to. | | Oracle | [Oracle Configuration](#Oracle-Configuration) | | Oracle module configuration. See the [Oracle Configuration](#Oracle-Configuration) section for details. | | P2PNotary | [P2P Notary Configuration](#P2P-Notary-Configuration) | | P2P Notary module configuration. See the [P2P Notary Configuration](#P2P-Notary-Configuration) section for details. | @@ -145,7 +145,7 @@ RPC: KeyFile: serv.key ``` where: -- `Enabled` denotes whether RPC server should be started. +- `Enabled` denotes whether an RPC server should be started. - `Address` is an RPC server address to be running at. - `EnableCORSWorkaround` enables Cross-Origin Resource Sharing and is useful if you're accessing RPC interface from the browser. @@ -202,14 +202,14 @@ protocol-related settings described in the table below. | Section | Type | Default value | Description | Notes | | --- | --- | --- | --- | --- | -| CommitteeHistory | map[uint32]int | none | Number of committee members after given height, for example `{0: 1, 20: 4}` sets up a chain with one committee member since the genesis and then changes the setting to 4 committee members at the height of 20. `StandbyCommittee` committee setting must have the number of keys equal or exceeding the highest value in this option. Blocks numbers where the change happens must be divisble by the old and by the new values simultaneously. If not set, committee size is derived from the `StandbyCommittee` setting and never changes. | +| CommitteeHistory | map[uint32]int | none | Number of committee members after the given height, for example `{0: 1, 20: 4}` sets up a chain with one committee member since the genesis and then changes the setting to 4 committee members at the height of 20. `StandbyCommittee` committee setting must have the number of keys equal or exceeding the highest value in this option. Blocks numbers where the change happens must be divisible by the old and by the new values simultaneously. If not set, committee size is derived from the `StandbyCommittee` setting and never changes. | | GarbageCollectionPeriod | `uint32` | 10000 | Controls MPT garbage collection interval (in blocks) for configurations with `RemoveUntraceableBlocks` enabled and `KeepOnlyLatestState` disabled. In this mode the node stores a number of MPT trees (corresponding to `MaxTraceableBlocks` and `StateSyncInterval`), but the DB needs to be clean from old entries from time to time. Doing it too often will cause too much processing overhead, doing it too rarely will leave more useless data in the DB. | | KeepOnlyLatestState | `bool` | `false` | Specifies if MPT should only store latest state. If true, DB size will be smaller, but older roots won't be accessible. This value should remain th e same for the same database. | Conflicts with `P2PStateExchangeExtensions`. | | Magic | `uint32` | `0` | Magic number which uniquely identifies NEO network. | | MaxBlockSize | `uint32` | `262144` | Maximum block size in bytes. | | MaxBlockSystemFee | `int64` | `900000000000` | Maximum overall transactions system fee per block. | -| MaxTraceableBlocks | `uint32` | `2102400` | Length of the chain accessible to smart contracts. | `RemoveUntraceableBlocks` should be enabled to use this setting. | +| MaxTraceableBlocks | `uint32` | `2102400` | Length of the chain accessible to smart contracts. | `RemoveUntraceableBlocks` should be enabled to use this setting. | | MaxTransactionsPerBlock | `uint16` | `512` | Maximum number of transactions per block. | | MemPoolSize | `int` | `50000` | Size of the node's memory pool where transactions are stored before they are added to block. | | NativeActivations | `map[string][]uint32` | ContractManagement: [0]
StdLib: [0]
CryptoLib: [0]
LedgerContract: [0]
NeoToken: [0]
GasToken: [0]
PolicyContract: [0]
RoleManagement: [0]
OracleContract: [0] | The list of histories of native contracts updates. Each list item shod be presented as a known native contract name with the corresponding list of chain's heights. The contract is not active until chain reaches the first height value specified in the list. | `Notary` is supported. | @@ -223,8 +223,8 @@ e same for the same database. | Conflicts with `P2PStateExchangeExtensions`. | | SeedList | `[]string` | [] | List of initial nodes addresses used to establish connectivity. | | StandbyCommittee | `[]string` | [] | List of public keys of standby committee validators are chosen from. | | StateRootInHeader | `bool` | `false` | Enables storing state root in block header. | Experimental protocol extension! | -| StateSyncInterval | `int` | `40000` | The number of blocks between state heights available for MPT state data synchronization. | `P2PStateExchangeExtensions` should be enabled to use this setting. | +| StateSyncInterval | `int` | `40000` | The number of blocks between state heights available for MPT state data synchronization. | `P2PStateExchangeExtensions` should be enabled to use this setting. | | ValidatorsCount | `int` | `0` | Number of validators set for the whole network lifetime, can't be set if `ValidatorsHistory` setting is used. | | ValidatorsHistory | map[uint32]int | none | Number of consensus nodes to use after given height (see `CommitteeHistory` also). Heights where the change occurs must be divisible by the number of committee members at that height. Can't be used with `ValidatorsCount` not equal to zero. | -| VerifyBlocks | `bool` | `false` | Denotes whether to verify received blocks. | -| VerifyTransactions | `bool` | `false` | Denotes whether to verify transactions in received blocks. | +| VerifyBlocks | `bool` | `false` | Denotes whether to verify the received blocks. | +| VerifyTransactions | `bool` | `false` | Denotes whether to verify transactions in the received blocks. | diff --git a/docs/notary.md b/docs/notary.md index ad5f9e14d..49ffbb991 100644 --- a/docs/notary.md +++ b/docs/notary.md @@ -15,7 +15,7 @@ The original problem definition: > any interaction, which is the case for oracle nodes or NeoFS inner ring nodes. > > As some of the services using this mechanism can be quite sensitive to the -> latency of their requests processing it should be possible to construct complete +> latency of their requests processing, it should be possible to construct a complete > transaction within the time frame between two consecutive blocks. @@ -26,10 +26,10 @@ doing the actual work. It uses generic `Conflicts` and `NotValidBefore` transaction attributes for its purposes as well as an additional special one (`Notary assisted`). -A new designated role is added, `P2PNotary`. It can have arbitrary number of +A new designated role is added, `P2PNotary`. It can have an arbitrary number of keys associated with it. -Using the service costs some GAS, so below we operate with `FEE` as a unit of cost +To use the service, one should pay some GAS, so below we operate with `FEE` as a unit of cost for this service. `FEE` is set to be 0.1 GAS. We'll also use `NKeys` definition as the number of keys that participate in the @@ -43,12 +43,12 @@ witnesses that's K+N*L. #### Conflicts -This attribute makes the chain only accept one transaction of the two conflicting +This attribute makes the chain accept one transaction of the two conflicting only and adds an ability to give a priority to any of the two if needed. This attribute was originally proposed in [neo-project/neo#1991](https://github.com/neo-project/neo/issues/1991). -The attribute has Uint256 data inside of it containing the hash of conflicting +The attribute has Uint256 data inside containing the hash of conflicting transaction. It is allowed to have multiple attributes of this type. #### NotValidBefore @@ -59,19 +59,19 @@ was originally proposed in The attribute has uint32 data inside which is the block height starting from which the transaction is considered to be valid. It can be seen as the opposite -of `ValidUntilBlock`, using both allows to have a window of valid block numbers +of `ValidUntilBlock`. Using both allows to have a window of valid block numbers that this transaction could be accepted into. Transactions with this attribute are not accepted into mempool before specified block is persisted. It can be used to create some transactions in advance with a guarantee that they -won't be accepted until specified block. +won't be accepted until the specified block. #### NotaryAssisted -This attribute contains one byte containing the number of transactions collected -by the service. It could be 0 for fallback transaction or `NKeys` for normal +This attribute holds one byte containing the number of transactions collected +by the service. It could be 0 for fallback transaction or `NKeys` for a normal transaction that completed its P2P signature collection. Transactions using this -attribute need to pay an additional network fee of (`NKeys`+1)×`FEE`. This attribute +attribute need to pay additional network fee of (`NKeys`+1)×`FEE`. This attribute could be only be used by transactions signed by the notary native contract. ### Native Notary contract @@ -109,9 +109,9 @@ This payload has two incomplete transactions inside: than the current chain height and it must have `Conflicts` attribute with the hash of the main transaction. It at the same time must have `Notary assisted` attribute with a count of zero. -- *Main tx*. This is the one that actually needs to be completed, it: +- *Main tx*. This is the one that actually needs to be completed; it: 1. *either* doesn't have all witnesses attached - 2. *or* it only has a partial multisignature + 2. *or* has a partial multisignature only 3. *or* have not all witnesses attached and some of the rest are partial multisignature This transaction must have `Notary assisted` attribute with a count of `NKeys` @@ -124,19 +124,19 @@ construct and send the payload. Node module with the designated key monitors the network for `P2PNotaryRequest` payloads. It maintains a list of current requests grouped by main transaction -hash, when it receives enough requests to correctly construct all transaction -witnesses it does so, adds a witness of its own (for Notary contract witness) and +hash. When it receives enough requests to correctly construct all transaction +witnesses, it does so, adds a witness of its own (for Notary contract witness) and sends the resulting transaction to the network. If the main transaction with all witnesses attached still can't be validated -because of fee (or other) issues, the node waits for `NotValidBefore` block of +due to any fee (or other) issues, the node waits for `NotValidBefore` block of the fallback transaction to be persisted. If `NotValidBefore` block is persisted and there are still some signatures missing (or the resulting transaction is invalid), the module sends all the associated fallback transactions for the main transaction. -After processing service request is deleted from the module. +After processing, service request is deleted from the module. See the [NeoGo P2P signature extensions](#NeoGo P2P signature extensions) on how to enable notary-related extensions on chain and @@ -145,7 +145,7 @@ set up Notary service node. ## Environment setup -To run P2P signature collection service on your network you need to do: +To run P2P signature collection service on your network, you need to do: * Set up [`P2PSigExtensions`](#NeoGo P2P signature extensions) for all nodes in the network. * Set notary node keys in `RoleManagement` native contract. @@ -159,7 +159,7 @@ notary requests to the network. ### NeoGo P2P signature extensions As far as Notary service is an extension of the standard NeoGo node, it should be -enabled and properly configured before the usage. +enabled and properly configured before usage. #### Configuration @@ -172,7 +172,7 @@ Notary contract and designate `P2PNotary` node role in RoleManagement native contract. If you use custom `NativeActivations` subsection of the `ProtocolConfiguration` -section in your node config, then specify the height of the Notary contract +section in your node config, specify the height of the Notary contract activation, e.g. `0`. Note, that even if `P2PSigExtensions` config subsection enables notary-related @@ -201,13 +201,13 @@ To enable notary service node functionality refer to the ### NeoGo Notary service node module NeoGo node can act as notary service node (the node that accumulates notary -requests, collects signatures and releases fully-signed transactions). It has to -have a wallet with key belonging to one of network's designated notary nodes +requests, collects signatures and releases fully-signed transactions). It must +have a wallet with a key belonging to one of network's designated notary nodes (stored in `RoleManagement` native contract). Also, the node must be connected to -the network with enabled P2P signature extensions, otherwise problems with states +a network with enabled P2P signature extensions, otherwise problems with states and peer disconnections will occur. -Notary service node doesn't need [RPC service](rpc.md) to be enabled, because it +Notary service node doesn't need [RPC service](rpc.md) to be enabled because it receives notary requests and broadcasts completed transactions via P2P protocol. However, enabling [RPC service](rpc.md) allows to send notary requests directly to the notary service node and avoid P2P communication delays. @@ -241,7 +241,7 @@ P2PNotary: Below are presented all stages each P2P signature collection request goes through. Use stages 1 and 2 to create, sign and submit P2P notary request. Stage 3 is -performed by the notary service, does not require user's intervention and is given +performed by the notary service; it does not require user's intervention and is given for informational purposes. Stage 4 contains advice to check for notary request results. @@ -252,221 +252,221 @@ sender's deposit to the Notary native contract is used. Before the notary reques submitted, you need to deposit enough GAS to the contract, otherwise, request won't pass verification. -Notary native contract supports `onNEP17Payment` method, thus to deposit funds to -the Notary native contract, transfer desired amount of GAS to the contract +Notary native contract supports `onNEP17Payment` method. Thus, to deposit funds to +the Notary native contract, transfer the desired amount of GAS to the contract address. Use [func (*Client) TransferNEP17](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.TransferNEP17) with the `data` parameter matching the following requirements: - `data` should be an array of two elements: `to` and `till`. -- `to` denotes the receiver of the deposit. It can be nil in case if `to` equals - to the GAS sender. +- `to` denotes the receiver of the deposit. It can be nil in case `to` equals + the GAS sender. - `till` denotes chain's height before which deposit is locked and can't be withdrawn. `till` can't be set if you're not the deposit owner. Default `till` - value is current chain height + 5760. `till` can't be less than current chain - height. `till` can't be less than currently set `till` value for that deposit if + value is the current chain height + 5760. `till` can't be less than the current chain + height. `till` can't be less than the currently set `till` value for that deposit if the deposit already exists. Note, that the first deposit call for the `to` address can't transfer less than 2×`FEE` GAS. Deposit is allowed for renewal, i.e. consequent `deposit` calls for the same `to` -address add up specified amount to the already deposited value. +address add up a specified amount to the already deposited value. -After GAS transfer successfully submitted to the chain, use [Notary native +After GAS transfer is successfully submitted to the chain, use [Notary native contract API](#Native Notary contract) to manage your deposit. -Note, that regular operation flow requires deposited amount of GAS to be +Note, that regular operation flow requires the deposited amount of GAS to be sufficient to pay for *all* fallback transactions that are currently submitted (all in-flight notary requests). The default deposit sum for one fallback transaction should be enough to pay the fallback transaction fees which are system fee and network fee. Fallback network fee includes (`NKeys`+1)×`FEE` = (0+1)×`FEE` = `FEE` GAS for `NotaryAssisted` attribute usage and regular fee for the fallback size. -If you need to submit several notary requests, ensure that deposited amount is +If you need to submit several notary requests, ensure that the deposited amount is enough to pay for all fallbacks. If the deposited amount is not enough to pay the -fallback fees, then `Insufficiend funds` error will be returned from the RPC node +fallback fees, `Insufficiend funds` error will be returned from the RPC node after notary request submission. ### 2. Request submission Once several parties want to sign one transaction, each of them should generate -the transaction, wrap it into `P2PNotaryRequest` payload and send to the known RPC +the transaction, wrap it into `P2PNotaryRequest` payload and send it to the known RPC server via [`submitnotaryrequest` RPC call](./rpc.md#submitnotaryrequest-call). -Note, that all parties must generate the same main transaction, while fallbacks +Note, that all parties must generate the same main transaction while fallbacks can differ. -To create notary request, you can use [NeoGo RPC client](./rpc.md#Client). Follow +To create a notary request, you can use [NeoGo RPC client](./rpc.md#Client). Follow the steps to create a signature request: -1. Prepare list of signers with scopes for the main transaction (i.e. the +1. Prepare a list of signers with scopes for the main transaction (i.e. the transaction that signatures are being collected for, that will be `Signers` transaction field). Use the following rules to construct the list: - * First signer is the one who pays transaction fees. - * Each signer is either multisignature or standard signature or a contract + * First signer is the one who pays the transaction fees. + * Each signer is either a multisignature or a standard signature or a contract signer. * Multisignature and signature signers can be combined. * Contract signer can be combined with any other signer. Include Notary native contract in the list of signers with the following constraints: - * Notary signer hash is the hash of native Notary contract that can be fetched + * Notary signer hash is the hash of a native Notary contract that can be fetched from [func (*Client) GetNativeContractHash](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.GetNativeContractHash). - * Notary signer must have `None` scope. - * Notary signer shouldn't be placed at the beginning of the signer list, + * A notary signer must have `None` scope. + * A notary signer shouldn't be placed at the beginning of the signer list because Notary contract does not pay main transaction fees. Other positions - in the signer list are available for Notary signer. -2. Construct script for the main transaction (that will be `Script` transaction + in the signer list are available for a Notary signer. +2. Construct a script for the main transaction (that will be `Script` transaction field) and calculate system fee using regular rules (that will be `SystemFee` transaction field). Probably, you'll perform one of these actions: 1. If the script is a contract method call, use `invokefunction` RPC API [func (*Client) InvokeFunction](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.InvokeFunction) - and fetch script and gas consumed from the result. + and fetch the script and the gas consumed from the result. 2. If the script is more complicated than just a contract method call, construct the script manually and use `invokescript` RPC API [func (*Client) InvokeScript](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.InvokeScript) - to fetch gas consumed from the result. + to fetch the gas consumed from the result. 3. Or just construct the script and set system fee manually. 3. Calculate the height main transaction is valid until (that will be `ValidUntilBlock` transaction field). Consider the following rules for `VUB` value estimation: - * `VUB` value must not be lower than current chain height. + * `VUB` value must not be lower than the current chain height. * The whole notary request (including fallback transaction) is valid until the same `VUB` height. * `VUB` value must be lower than notary deposit expiration height. This - condition guarantees that deposit won't be withdrawn before notary + condition guarantees that the deposit won't be withdrawn before notary service payment. * All parties must provide the same `VUB` for the main transaction. 4. Construct the list of main transaction attributes (that will be `Attributes` transaction field). The list must include `NotaryAssisted` attribute with - `NKeys` equals to the sum number of keys to be collected excluding notary and + `NKeys` equals the overall number of the keys to be collected excluding notary and other contract-based witnesses. For m out of n multisignature request - `NKeys = n`. For multiple standard signature request signers `NKeys` equals to + `NKeys = n`. For multiple standard signature request, signers `NKeys` equals the standard signature signers count. -5. Construct the list of accounts (`wallet.Account` structure from the `wallet` +5. Construct a list of accounts (`wallet.Account` structure from the `wallet` package) to calculate network fee for the transaction - using following rules. This list will be used in the next step. - - Number and order of the accounts should match transaction signers + using the following rules. This list will be used in the next step. + - The number and the order of the accounts should match the transaction signers constructed at step 1. - - Account for contract signer should have `Contract` field with `Deployed` set + - An account for a contract signer should have `Contract` field with `Deployed` set to `true` if the corresponding contract is deployed on chain. - - Account for signature or multisignature signer should have `Contract` field + - An account for a signature or a multisignature signer should have `Contract` field with `Deployed` set to `false` and `Script` set to the signer's verification script. - - Account for notary signer is **just a placeholder** and should have + - An account for a notary signer is **just a placeholder** and should have `Contract` field with `Deployed` set to `false`, i.e. the default value for `Contract` field. That's needed to skip notary verification during regular network fee calculation at the next step. 7. Calculate network fee for the transaction (that will be `NetworkFee` transaction field). Network fee consists of several parts: - - *Notary network fee.* That's amount of GAS need to be paid for + - *Notary network fee.* That's the amount of GAS needed to be paid for `NotaryAssisted` attribute usage and for notary contract witness verification (that is to be added by the notary node in the end of signature collection process). Use [func (*Client) CalculateNotaryFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.CalculateNotaryFee) - to calculate notary network fee. Use `NKeys` estimated on the step 4 as an + to calculate notary network fee. Use `NKeys` estimated at step 4 as an argument. - - *Regular network fee.* That's amount of GAS to be paid for other witnesses + - *Regular network fee.* That's the amount of GAS to be paid for other witnesses verification. Use [func (*Client) AddNetworkFee](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.AddNetworkFee) to calculate regular network fee and add it to the transaction. Use partially-filled main transaction from the previous steps as `tx` argument. Use notary network fee calculated at the previous substep as `extraFee` - argument. Use the list of accounts constructed at the step 5 as `accs` + argument. Use the list of accounts constructed at step 5 as `accs` argument. -8. Fill in main transaction `Nonce` field. -9. Construct the list of main transactions witnesses (that will be `Scripts` +8. Fill in the main transaction `Nonce` field. +9. Construct a list of main transactions witnesses (that will be `Scripts` transaction field). Use the following rules: - - Contract-based witness should have `Invocation` script that pushes arguments + - A contract-based witness should have `Invocation` script that pushes arguments on stack (it may be empty) and empty `Verification` script. If multiple notary - requests provide different `Invocation` scripts then the first one will be used + requests provide different `Invocation` scripts, the first one will be used to construct contract-based witness. - - **Notary contract witness** (which is also a contract-based witness) should + - A **Notary contract witness** (which is also a contract-based witness) should have empty `Verification` script. `Invocation` script should be of the form [opcode.PUSHDATA1, 64, make([]byte, 64)...], i.e. to be a placeholder for - notary contract signature. - - Standard signature witness must have regular `Verification` script filled + a notary contract signature. + - A standard signature witness must have regular `Verification` script filled even if the `Invocation` script is to be collected from other notary requests. `Invocation` script either should push signature bytes on stack **or** (in - case if the signature is to be collected) **should be empty**. - - Multisignature witness must have regular `Verification` script filled even + case the signature is to be collected) **should be empty**. + - A multisignature witness must have regular `Verification` script filled even if `Invocation` script is to be collected from other notary requests. `Invocation` script either should push on stack signature bytes (one - signature at max per one resuest) **or** (in case if there's no ability to + signature at max per one request) **or** (in case there's no ability to provide proper signature) **should be empty**. 10. Define lifetime for the fallback transaction. Let the `fallbackValidFor` be the lifetime. Let `N` be the current chain's height and `VUB` be - `ValidUntilBlock` value estimated at the step 3. Then notary node is trying to + `ValidUntilBlock` value estimated at step 3. Then, the notary node is trying to collect signatures for the main transaction from `N` up to `VUB-fallbackValidFor`. In case of failure after `VUB-fallbackValidFor`-th - block is accepted, notary node stops attempts to complete main transaction and + block is accepted, the notary node abandons attempts to complete the main transaction and tries to push all associated fallbacks. Use the following rules to define `fallbackValidFor`: - `fallbackValidFor` shouldn't be more than `MaxNotValidBeforeDelta` value. - Use [func (*Client) GetMaxNotValidBeforeDelta](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.GetMaxNotValidBeforeDelta) to check `MaxNotValidBefore` value. -11. Construct script for the fallback transaction. Script may do something useful, - i.g. invoke method of a contract, but if you don't need to perform something +11. Construct a script for the fallback transaction. The script may do something useful, + i.g. invoke method of a contract. However, if you don't need to perform anything special on fallback invocation, you can use simple `opcode.RET` script. 12. Sign and submit P2P notary request. Use [func (*Client) SignAndPushP2PNotaryRequest](https://pkg.go.dev/github.com/nspcc-dev/neo-go@v0.97.2/pkg/rpc/client#Client.SignAndPushP2PNotaryRequest) for it. - - Use signed main transaction from step 8 as `mainTx` argument. - - Use fallback script from step 10 as `fallbackScript` argument. + - Use the signed main transaction from step 8 as `mainTx` argument. + - Use the fallback script from step 10 as `fallbackScript` argument. - Use `-1` as `fallbackSysFee` argument to define system fee by test - invocation or provide custom value. + invocation or provide any custom value. - Use `0` as `fallbackNetFee` argument not to add extra network fee to the fallback. - - Use `fallbackValidFor` estimated at step 9 as `fallbackValidFor` argument. + - Use the `fallbackValidFor` estimated at step 9 as `fallbackValidFor` argument. - Use your account you'd like to send request (and fallback transaction) from to sign the request (and fallback transaction). - `SignAndPushP2PNotaryRequest` will construct and sign fallback transaction, - construct and sign P2PNotaryRequest and submit it to the RPC node. The + `SignAndPushP2PNotaryRequest` will construct and sign a fallback transaction, + construct and sign a P2PNotaryRequest and submit it to the RPC node. The resulting notary request and an error are returned. -After P2PNotaryRequests are sent, participants should then wait for one of their +After P2PNotaryRequests are sent, participants should wait for one of their transactions (main or fallback) to get accepted into one of subsequent blocks. ### 3. Signatures collection and transaction release -Valid P2PNotaryRequest payload is distributed via P2P network using standard -broadcasting mechanisms until it reaches designated notary nodes that have the +A valid P2PNotaryRequest payload is distributed via P2P network using standard +broadcasting mechanisms until it reaches the designated notary nodes that have the respective node module active. They collect all payloads for the same main transaction until enough signatures are collected to create proper witnesses for -it. They then attach all witnesses required and send this transaction as usual +it. Then, they attach all witnesses required and send this transaction as usual and monitor subsequent blocks for its inclusion. All the operations leading to successful transaction creation are independent -of the chain and could easily be done within one block interval, so if the -first service request is sent at current height `H` it's highly likely that the -main transaction will be a part of `H+1` block. +of the chain and could easily be done within one block interval. So, if the +first service request is sent at the current height `H`, the main transaction +is highly likely to be a part of `H+1` block. ### 4. Results monitoring -Once P2PNotaryRequest reached RPC node, it is added to the notary request pool. -Completed or outdated requests are being removed from the pool. Use +Once the P2PNotaryRequest reaches RPC node, it is added to the notary request pool. +Completed or outdated requests are removed from the pool. Use [NeoGo notification subsystem](./notifications.md) to track request addition and removal: - Use RPC `subscribe` method with `notary_request_event` stream name parameter to subscribe to `P2PNotaryRequest` payloads that are added or removed from the notary request pool. -- Use `sender` or `signer` filters to filter out notary request with desired +- Use `sender` or `signer` filters to filter out a notary request with the desired request senders or main tx signers. -Use the notification subsystem to track that main or fallback transaction -accepted to the chain: +Use the notification subsystem to track that the main or the fallback transaction +is accepted to the chain: - Use RPC `subscribe` method with `transaction_added` stream name parameter to subscribe to transactions that are accepted to the chain. -- Use `sender` filter with Notary native contract hash to filter out fallback - transactions sent by Notary node. Use `signer` filter with notary request - sender address to filter out fallback transactions sent by the specified +- Use `sender` filter with the Notary native contract hash to filter out fallback + transactions sent by the Notary node. Use `signer` filter with the notary request + sender address to filter out the fallback transactions sent by the specified sender. -- Use `sender` or `signer` filters to filter out main transaction with desired - sender or signers. You can also filter out main transaction using Notary +- Use `sender` or `signer` filters to filter out the main transaction with the desired + sender or signers. You can also filter out the main transaction using Notary contract `signer` filter. -- Don't rely on `sender` and `signer` filters only, check also that received - transaction has `NotaryAssisted` attribute with expected `NKeys` value. +- Don't rely on `sender` and `signer` filters only, also check that the received + transaction has `NotaryAssisted` attribute with the expected `NKeys` value. Use the notification subsystem to track main or fallback transaction execution results. @@ -480,31 +480,31 @@ Several use-cases where Notary subsystem can be applied are described below. ### Committee-signed transactions -The signature collection problem occures every time committee participants need -to submit transaction with `m out of n` multisignature, i.g.: -- transfer initial supply of NEO and GAS from committee multisignature account to +The signature collection problem occurs every time committee participants need +to submit a transaction with `m out of n` multisignature, i.g.: +- transfer initial supply of NEO and GAS from a committee multisignature account to other addresses on new chain start - tune valuable chain parameters like gas per block, candidate register price, minimum contract deployment fee, Oracle request price, native Policy values etc - invoke non-native contract methods that require committee multisignature witness -Current solution supposes off-chain non-P2P signature collection (either manual +Current solution offers off-chain non-P2P signature collection (either manual or using some additional network connectivity). It has an obvious downside of reliance on something external to the network. If it's manual, it's slow and -error-prone, if it's automated, it requires additional protocol for all the -parties involved. For the protocol used by oracle nodes that also means -explicitly exposing nodes to each other. +error-prone; if it's automated, it requires additional protocol for all the +parties involved. For the protocol used by oracle nodes, it also means +nodes explicitly exposing to each other. -With Notary service all signature collection logic is unified and is on chain already, -the only thing that committee participants should perform is to create and submit -P2P notary request (can be done independently). Once sufficient number of signatures -is collected by the service, desired transaction will be applied and pass committee +With the Notary service all signature collection logic is unified and is on chain already. +The only thing that committee participants should perform is to create and submit +a P2P notary request (can be done independently). Once the sufficient number of signatures +is collected by the service, the desired transaction will be applied and pass committee witness verification. ### NeoFS Inner Ring nodes Alphabet nodes of the Inner Ring signature collection is a particular case of committee-signed -transactions. Alphabet nodes multisignature is used for the various cases, such as: +transactions. Alphabet nodes multisignature is used for various cases, such as: - main chain and side chain funds synchronization and withdrawal - bootstrapping new storage nodes to the network - network map management and epoch update @@ -513,7 +513,7 @@ transactions. Alphabet nodes multisignature is used for the various cases, such Non-notary on-chain solution for Alphabet nodes multisignature forming is imitated via contracts collecting invocations of their methods signed by standard -signature of each Alphabet node. Once sufficient number of invocations is +signature of each Alphabet node. Once the sufficient number of invocations is collected, the invocation is performed. The described solution has several drawbacks: @@ -522,7 +522,7 @@ The described solution has several drawbacks: be duplicated) because we can't create transactions from transactions (thus using proper multisignature account is not possible) - for `m out of n` multisignature we need at least `m` transactions instead of - one we really wanted to have, but in reality we'll create and process `n` of + one we really wanted to have; but actually we'll create and process `n` of them, so this adds substantial overhead to the chain - some GAS is inevitably wasted because any invocation could either go the easy path (just adding a signature to the list) or really invoke the function we @@ -531,7 +531,7 @@ The described solution has several drawbacks: Notary on-chain Alphabet multisignature collection solution [uses Notary subsystem](https://github.com/nspcc-dev/neofs-node/pull/404) to -successfully solve these problems, e.g. to calculate precisely amount of GAS to +successfully solve these problems, e.g. to calculate precisely the amount of GAS to pay for contract invocation witnessed by Alphabet nodes (see [nspcc-dev/neofs-node#47](https://github.com/nspcc-dev/neofs-node/issues/47)), to reduce container creation delay @@ -540,5 +540,5 @@ etc. ### Contract-sponsored (free) transactions -The original problem and solution are described in the -[neo-project/neo#2577](https://github.com/neo-project/neo/issues/2577) discussion. \ No newline at end of file +The original problem and solution are described in +[neo-project/neo#2577](https://github.com/neo-project/neo/issues/2577) discussion. diff --git a/docs/notifications.md b/docs/notifications.md index 6aedecc52..7c73c5142 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -34,15 +34,15 @@ Filters use conjunctional logic. announcing the block itself * transaction notifications are only announced for successful transactions * all announcements are being done in the same order they happen on the chain - At first transaction execution is announced, then followed by notifications - generated during this execution, then followed by transaction announcement. + First, transaction execution is announced. It is then followed by notifications + generated during this execution. Next, follows the transaction announcement. Transaction announcements are ordered the same way they're in the block. * unsubscription may not cancel pending, but not yet sent events ## Subscription management -To receive events clients need to subscribe to them first via `subscribe` -method. Upon successful subscription clients receive subscription ID for +To receive events, clients need to subscribe to them first via `subscribe` +method. Upon successful subscription, clients receive subscription ID for subsequent management of this subscription. Subscription is only valid for connection lifetime, no long-term client identification is being made. @@ -59,18 +59,18 @@ Recognized stream names: Filter: `primary` as an integer with primary (speaker) node index from ConsensusData. * `transaction_added` - Filter: `sender` field containing string with hex-encoded Uint160 (LE + Filter: `sender` field containing a string with hex-encoded Uint160 (LE representation) for transaction's `Sender` and/or `signer` in the same format for one of transaction's `Signers`. * `notification_from_execution` - Filter: `contract` field containing string with hex-encoded Uint160 (LE - representation) and/or `name` field containing string with execution - notification name. + Filter: `contract` field containing a string with hex-encoded Uint160 (LE + representation) and/or `name` field containing a string with execution + notification name. * `transaction_executed` Filter: `state` field containing `HALT` or `FAULT` string for successful and failed executions respectively. * `notary_request_event` - Filter: `sender` field containing string with hex-encoded Uint160 (LE + Filter: `sender` field containing a string with hex-encoded Uint160 (LE representation) for notary request's `Sender` and/or `signer` in the same format for one of main transaction's `Signers`. @@ -133,21 +133,22 @@ Example response: Events are sent as JSON-RPC notifications from the server with `method` field being used for notification names. Notification names are identical to stream names described for `subscribe` method with one important addition for -`event_missed` which can be sent for any subscription to signify that some -events were not delivered (usually when client isn't able to keep up with -event flow). +`event_missed`, which can be sent for any subscription to signify that some +events have not been delivered (usually when a client is unable to keep up with +the event flow). Verbose responses for various structures like blocks and transactions are used -to simplify working with notifications on client side. Returned structures -mostly follow the one used by standard Neo RPC calls, but may have some minor +to simplify working with notifications on the client side. Returned structures +mostly follow the one used by standard Neo RPC calls but may have some minor differences. If a server-side event matches several subscriptions from one client, it's only sent once. ### `block_added` notification -As a first parameter (`params` section) contains block converted to JSON -structure which is similar to verbose `getblock` response but with the + +The first parameter (`params` section) contains a block converted to a JSON +structure, which is similar to a verbose `getblock` response but with the following differences: * it doesn't have `size` field (you can calculate it client-side) * it doesn't have `nextblockhash` field (it's supposed to be the latest one @@ -238,8 +239,8 @@ Example: ### `transaction_added` notification -In the first parameter (`params` section) contains transaction converted to -JSON which is similar to verbose `getrawtransaction` response, but with the +The first parameter (`params` section) contains a transaction converted to +JSON, which is similar to a verbose `getrawtransaction` response, but with the following differences: * block's metadata is missing (`blockhash`, `confirmations`, `blocktime`) @@ -337,8 +338,8 @@ Example: ### `transaction_executed` notification -Contains the same result as from `getapplicationlog` method in the first -parameter and no other parameters. One difference from `getapplicationlog` is +It contains the same result as from `getapplicationlog` method in the first +parameter and no other parameters. The only difference from `getapplicationlog` is that it always contains zero in the `contract` field. Example: @@ -424,7 +425,7 @@ Example: ### `notary_request_event` notification -Contains two parameters: event type which could be one of "added" or "removed" and +It contains two parameters: event type, which could be one of "added" or "removed", and added (or removed) notary request. Example: diff --git a/docs/oracle.md b/docs/oracle.md index 023320729..8b55b0fb7 100644 --- a/docs/oracle.md +++ b/docs/oracle.md @@ -1,7 +1,7 @@ # NeoGo Oracle service -NeoGo node can act as oracle service node for https and neofs protocols. It -has to have a wallet with key belonging to one of network's designated oracle +NeoGo node can act as an oracle service node for https and neofs protocols. It +has to have a wallet with a key belonging to one of the network's designated oracle nodes (stored in `RoleManagement` native contract). It needs [RPC service](rpc.md) to be enabled and configured properly because @@ -10,7 +10,7 @@ transaction. ## Configuration -To enable oracle service add `Oracle` subsection to `ApplicationConfiguration` +To enable oracle service, add `Oracle` subsection to `ApplicationConfiguration` section of your node config. Parameters: @@ -19,14 +19,14 @@ Parameters: * `AllowPrivateHost`: boolean value, enables/disables private IPs (like 127.0.0.1 or 192.168.0.1) for https requests, it defaults to false and it's false on public networks, but you can enable it for private ones. - * `AllowedContentTypes`: list of allowed MIME types. Only `application/json` + * `AllowedContentTypes`: a list of allowed MIME types. Only `application/json` is allowed by default. Can be left empty to allow everything. - * `Nodes`: list of oracle node RPC endpoints, it's used for oracle node + * `Nodes`: a list of oracle node RPC endpoints, it's used for oracle node communication. All oracle nodes should be specified there. * `NeoFS`: a subsection of its own for NeoFS configuration with two parameters: - `Timeout`: request timeout, like "5s" - - `Nodes`: list of NeoFS nodes (their gRPC interfaces) to get data from, + - `Nodes`: a list of NeoFS nodes (their gRPC interfaces) to get data from, one node is enough to operate, but they're used in round-robin fashion, so you can spread the load by specifying multiple nodes * `MaxTaskTimeout`: maximum time a request can be active (retried to @@ -67,7 +67,7 @@ Parameters: ## Operation -To run oracle service on your network you need to: +To run oracle service on your network, you need to: * set oracle node keys in `RoleManagement` contract - * configure and run appropriate number of oracle nodes with keys specified in + * configure and run an appropriate number of oracle nodes with keys specified in `RoleManagement` contract diff --git a/docs/release-instruction.md b/docs/release-instruction.md index 6310de5b9..cabdbc928 100644 --- a/docs/release-instruction.md +++ b/docs/release-instruction.md @@ -1,11 +1,11 @@ # Release instructions -This documents outlines the neo-go release process, it can be used as a todo +This document outlines the neo-go release process. It can be used as a todo list for a new release. ## Pre-release checks -These should run successfuly: +These should run successfully: * build * unit-tests * lint @@ -15,10 +15,10 @@ These should run successfuly: Add an entry to the CHANGELOG.md following the style established there. Add a codename, version and release date in the heading. Write a paragraph -describing the most significant changes done in this release. Then add -sections with new features and bugs fixed describing each change in detail and +describing the most significant changes done in this release. Then, add +sections with new features implemented and bugs fixed describing each change in detail and with a reference to Github issues. Add generic improvements section for -changes that are not directly visible to the node end-user such as performance +changes that are not directly visible to the node end-user, such as performance optimizations, refactoring and API changes. Add a "Behaviour changes" section if there are any incompatible changes in default settings or the way commands operate. @@ -34,8 +34,8 @@ Use `vX.Y.Z` tag following the semantic versioning standard. ## Push changes and release tag to Github This step should bypass the default PR mechanism to get a correct result (so -that releasing requires admin privileges for the project), both the `master` -branch update and tag must be pushed simultaneously like this: +that releasing requires admin privileges for the project). Both the `master` +branch update and the tag must be pushed simultaneously like this: $ git push origin master v0.70.1 @@ -61,10 +61,10 @@ Copy the github release page link to: ## Deployment -Deploy updated version to the mainnet/testnet. +Deploy the updated version to the mainnet/testnet. ## Post-release The first commit after the release must be tagged with `X.Y.Z+1-pre` tag for -proper semantic-versioned builds, so it's good to make some minor +proper semantic-versioned builds. So, it's good to make some minor documentation update after the release and push it with this new tag. diff --git a/docs/rpc.md b/docs/rpc.md index 4fb8c8a86..3e0b2fa81 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -78,14 +78,14 @@ which would yield the response: ##### `invokefunction` -neo-go's implementation of `invokefunction` does not return `tx` +neo-go implementation of `invokefunction` does not return `tx` field in the answer because that requires signing the transaction with some -key in the server which doesn't fit the model of our node-client interactions. -Lacking this signature the transaction is almost useless, so there is no point +key in the server, which doesn't fit the model of our node-client interactions. +If this signature is lacking, the transaction is almost useless, so there is no point in returning it. -It's possible to use `invokefunction` not only with contract scripthash, but also -with contract name (for native contracts) or contract ID (for all contracts). This +It's possible to use `invokefunction` not only with a contract scripthash, but also +with a contract name (for native contracts) or a contract ID (for all contracts). This feature is not supported by the C# node. ##### `getcontractstate` @@ -95,7 +95,7 @@ it only works for native contracts. ##### `getrawtransaction` -VM state is included to verbose response along with other transaction fields if +VM state is included into verbose response along with other transaction fields if the transaction is already on chain. ##### `getstateroot` @@ -107,30 +107,30 @@ where only index is accepted. This method doesn't work for the Ledger contract, you can get data via regular `getblock` and `getrawtransaction` calls. This method is able to get storage of -the native contract by its name (case-insensitive), unlike the C# node where +a native contract by its name (case-insensitive), unlike the C# node where it only possible for index or hash. #### `getnep11balances` and `getnep17balances` -neo-go's implementation of `getnep11balances` and `getnep17balances` does not +neo-go implementation of `getnep11balances` and `getnep17balances` does not perform tracking of NEP-11 and NEP-17 balances for each account as it is done -in the C# node. Instead, neo-go node maintains the list of standard-compliant +in the C# node. Instead, a neo-go node maintains a list of standard-compliant contracts, i.e. those contracts that have `NEP-11` or `NEP-17` declared in the supported standards section of the manifest. Each time balances are queried, -neo-go node asks every NEP-11/NEP-17 contract for the account balance by +the neo-go node asks every NEP-11/NEP-17 contract for the account balance by invoking `balanceOf` method with the corresponding args. Invocation GAS limit is set to be 3 GAS. All non-zero balances are included in the RPC call result. -Thus, if token contract doesn't have proper standard declared in the list of +Thus, if a token contract doesn't have proper standard declared in the list of supported standards but emits compliant NEP-11/NEP-17 `Transfer` notifications, the token balance won't be shown in the list of balances returned by the neo-go node (unlike the C# node behavior). However, transfer logs of such tokens are still available via respective `getnepXXtransfers` RPC calls. -The behaviour of the `LastUpdatedBlock` tracking for archival nodes as far as for +The behavior of the `LastUpdatedBlock` tracking for archival nodes as far as for governing token balances matches the C# node's one. For non-archival nodes and -other NEP-11/NEP-17 tokens if transfer's `LastUpdatedBlock` is lower than the -latest state synchronization point P the node working against, then +other NEP-11/NEP-17 tokens, if transfer's `LastUpdatedBlock` is lower than the +latest state synchronization point P the node working against, `LastUpdatedBlock` equals P. For NEP-11 NFTs `LastUpdatedBlock` is equal for all tokens of the same asset. @@ -139,7 +139,7 @@ all tokens of the same asset. ### Unsupported methods -Methods listed down below are not going to be supported for various reasons +Methods listed below are not going to be supported for various reasons and we're not accepting issues related to them. | Method | Reason | @@ -165,7 +165,7 @@ Some additional extensions are implemented as a part of this RPC server. This method returns cumulative system fee for all transactions included in a block. It can be removed in future versions, but at the moment you can use it -to see how much GAS is burned with particular block (because system fees are +to see how much GAS is burned with a particular block (because system fees are burned). #### `invokecontractverifyhistoric`, `invokefunctionhistoric` and `invokescripthistoric` calls @@ -198,11 +198,11 @@ payloads to be relayed from RPC to P2P. #### Limits and paging for getnep11transfers and getnep17transfers `getnep11transfers` and `getnep17transfers` RPC calls never return more than -1000 results for one request (within specified time frame). You can pass your +1000 results for one request (within the specified time frame). You can pass your own limit via an additional parameter and then use paging to request the next batch of transfers. -Example requesting 10 events for address NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc +An example of requesting 10 events for address NbTiM6h8r99kpRtb428XcsUk1TzKed2gTc within 0-1600094189000 timestamps: ```json diff --git a/docs/stateroots.md b/docs/stateroots.md index 9cc41930c..7930fa385 100644 --- a/docs/stateroots.md +++ b/docs/stateroots.md @@ -3,11 +3,11 @@ NeoGo supports state validation using N3 stateroots and can also act as state validator (run state validation service). -All NeoGo nodes always calculate MPT root hash for data stored by contracts, -unlike in Neo Legacy this behavior can't be turned off. They also process +All NeoGo nodes always calculate MPT root hash for data stored by contracts. +Unlike in Neo Legacy, this behavior can't be turned off. They also process stateroot messages broadcasted through the network and save validated -signatures from them if state root hash specified there matches the one signed -by validators (or shouts loud in the log if it doesn't, because it should be +signatures from them if the state root hash specified there matches the one signed +by validators (or shouts loud in the log if it doesn't because it should be the same). ## State validation service @@ -37,7 +37,7 @@ Parameters: To run state validation service on your network you need to: * set state validation node keys in `RoleManagement` contract - * configure and run appropriate number of state validation nodes with keys + * configure and run an appropriate number of state validation nodes with the keys specified in `RoleManagement` contract @@ -46,7 +46,7 @@ To run state validation service on your network you need to: NeoGo also supports protocol extension to include state root hashes right into header blocks. It's not compatible with regular Neo N3 state validation service and it's not compatible with public Neo N3 networks, but you can use -it on private networks if there is a need to. +it on private networks if needed. The option is `StateRootInHeader` and it's specified in `ProtocolConfiguration` section, set it to true and run your network with it diff --git a/docs/vm.md b/docs/vm.md index 68f403f00..d5d215e51 100644 --- a/docs/vm.md +++ b/docs/vm.md @@ -4,7 +4,7 @@ A cross platform virtual machine implementation for `NEF` compatible programs. # Installation -VM is provided as part of neo-go binary, so usual neo-go build instructions +VM is provided as a part of neo-go binary, so usual neo-go build instructions are applicable. # Running the VM @@ -118,7 +118,7 @@ NEO-GO-VM > run ``` ## Running programs with arguments -You can invoke smart contracts with arguments. Take the following ***roll the dice*** smartcontract as example. +You can invoke smart contracts with arguments. Take the following ***roll the dice*** smart contract as an example. ``` package rollthedice @@ -144,9 +144,9 @@ func RollDice(number int) { To invoke this contract we need to specify both the method and the arguments. The first parameter (called method or operation) is always of type -string. Notice that arguments can have different types, they can inferred -automatically (please refer to the `run` command help), but in you need to -pass parameter of specific type you can specify it in `run`'s arguments: +string. Notice that arguments can have different types. They can be inferred +automatically (please refer to the `run` command help), but if you need to +pass a parameter of a specific type you can specify it in `run`'s arguments: ``` NEO-GO-VM > run rollDice int:1 diff --git a/examples/nft-nd-nns/nns_test.go b/examples/nft-nd-nns/nns_test.go index 45219a0e8..bcb92afee 100644 --- a/examples/nft-nd-nns/nns_test.go +++ b/examples/nft-nd-nns/nns_test.go @@ -220,7 +220,7 @@ func TestSetGetRecord(t *testing.T) { c.Invoke(t, "1.2.3.4", "getRecord", "neo.com", int64(nns.A)) t.Run("SetRecord_compatibility", func(t *testing.T) { - // tests are got from the NNS C# implementation and changed accordingly to non-native implementation behaviour + // tests are got from the NNS C# implementation and changed accordingly to non-native implementation behavior testCases := []struct { Type nns.RecordType Name string diff --git a/examples/nft-nd/nft.go b/examples/nft-nd/nft.go index b8f8a7faf..b0e469328 100644 --- a/examples/nft-nd/nft.go +++ b/examples/nft-nd/nft.go @@ -1,7 +1,7 @@ /* Package nft contains non-divisible non-fungible NEP-11-compatible token implementation. This token can be minted with GAS transfer to contract address, -it will hash some data (including data provided in transfer) and produce +it will hash some data (including data provided in transfer) and produce a base64-encoded string that is your NFT. Since it's based on hashing and basically you own a hash it's HASHY. */ @@ -54,7 +54,7 @@ func TotalSupply() int { } // totalSupply is an internal implementation of TotalSupply operating with -// given context. The number itself is stored raw in the DB with totalSupplyPrefix +// the given context. The number itself is stored raw in the DB with totalSupplyPrefix // key. func totalSupply(ctx storage.Context) int { var res int @@ -66,28 +66,28 @@ func totalSupply(ctx storage.Context) int { return res } -// mkAccountPrefix creates DB key-prefix for account tokens specified +// mkAccountPrefix creates DB key-prefix for the account tokens specified // by concatenating accountPrefix and account address. func mkAccountPrefix(holder interop.Hash160) []byte { res := []byte(accountPrefix) return append(res, holder...) } -// mkBalanceKey creates DB key for account specified by concatenating balancePrefix +// mkBalanceKey creates DB key for the account specified by concatenating balancePrefix // and account address. func mkBalanceKey(holder interop.Hash160) []byte { res := []byte(balancePrefix) return append(res, holder...) } -// mkTokenKey creates DB key for token specified by concatenating tokenPrefix +// mkTokenKey creates DB key for the token specified by concatenating tokenPrefix // and token ID. func mkTokenKey(tokenID []byte) []byte { res := []byte(tokenPrefix) return append(res, tokenID...) } -// BalanceOf returns the number of tokens owned by specified address. +// BalanceOf returns the number of tokens owned by the specified address. func BalanceOf(holder interop.Hash160) int { if len(holder) != 20 { panic("bad owner address") @@ -96,7 +96,7 @@ func BalanceOf(holder interop.Hash160) int { return getBalanceOf(ctx, mkBalanceKey(holder)) } -// getBalanceOf returns balance of the account using database key. +// getBalanceOf returns the balance of an account using database key. func getBalanceOf(ctx storage.Context, balanceKey []byte) int { val := storage.Get(ctx, balanceKey) if val != nil { @@ -105,7 +105,7 @@ func getBalanceOf(ctx storage.Context, balanceKey []byte) int { return 0 } -// addToBalance adds amount to the account balance. Amount can be negative. +// addToBalance adds an amount to the account balance. Amount can be negative. func addToBalance(ctx storage.Context, holder interop.Hash160, amount int) { key := mkBalanceKey(holder) old := getBalanceOf(ctx, key) @@ -117,13 +117,13 @@ func addToBalance(ctx storage.Context, holder interop.Hash160, amount int) { } } -// addToken adds token to the account. +// addToken adds a token to the account. func addToken(ctx storage.Context, holder interop.Hash160, token []byte) { key := mkAccountPrefix(holder) storage.Put(ctx, append(key, token...), token) } -// removeToken removes token from the account. +// removeToken removes the token from the account. func removeToken(ctx storage.Context, holder interop.Hash160, token []byte) { key := mkAccountPrefix(holder) storage.Delete(ctx, append(key, token...)) @@ -137,7 +137,7 @@ func Tokens() iterator.Iterator { return iter } -// TokensOf returns an iterator with all tokens held by specified address. +// TokensOf returns an iterator with all tokens held by the specified address. func TokensOf(holder interop.Hash160) iterator.Iterator { if len(holder) != 20 { panic("bad owner address") @@ -148,8 +148,8 @@ func TokensOf(holder interop.Hash160) iterator.Iterator { return iter } -// getOwnerOf returns current owner of the specified token or panics if token -// ID is invalid. Owner is stored as value of the token key (prefix + token ID). +// getOwnerOf returns the current owner of the specified token or panics if token +// ID is invalid. The owner is stored as a value of the token key (prefix + token ID). func getOwnerOf(ctx storage.Context, token []byte) interop.Hash160 { key := mkTokenKey(token) val := storage.Get(ctx, key) @@ -159,13 +159,13 @@ func getOwnerOf(ctx storage.Context, token []byte) interop.Hash160 { return val.(interop.Hash160) } -// setOwnerOf writes current owner of the specified token into the DB. +// setOwnerOf writes the current owner of the specified token into the DB. func setOwnerOf(ctx storage.Context, token []byte, holder interop.Hash160) { key := mkTokenKey(token) storage.Put(ctx, key, holder) } -// OwnerOf returns owner of specified token. +// OwnerOf returns the owner of the specified token. func OwnerOf(token []byte) interop.Hash160 { ctx := storage.GetReadOnlyContext() return getOwnerOf(ctx, token) @@ -248,14 +248,14 @@ func OnNEP17Payment(from interop.Hash160, amount int, data interface{}) { postTransfer(nil, from, []byte(token), nil) // no `data` during minting } -// Verify allows owner to manage contract's address, including earned GAS -// transfer from contract's address to somewhere else. It just checks for transaction -// to also be signed by contract owner, so contract's witness should be empty. +// Verify allows an owner to manage a contract's address, including earned GAS +// transfer from the contract's address to somewhere else. It just checks for the transaction +// to also be signed by the contract owner, so contract's witness should be empty. func Verify() bool { return runtime.CheckWitness(contractOwner) } -// Destroy destroys the contract, only owner can do that. +// Destroy destroys the contract, only its owner can do that. func Destroy() { if !Verify() { panic("only owner can destroy") @@ -263,7 +263,7 @@ func Destroy() { management.Destroy() } -// Update updates the contract, only owner can do that. +// Update updates the contract, only its owner can do that. func Update(nef, manifest []byte) { if !Verify() { panic("only owner can update") diff --git a/examples/runtime/runtime.go b/examples/runtime/runtime.go index 3536bc1ea..9ecdd559d 100644 --- a/examples/runtime/runtime.go +++ b/examples/runtime/runtime.go @@ -40,7 +40,7 @@ func CheckWitness() bool { return false } -// Log logs given message. +// Log logs the given message. func Log(message string) { runtime.Log(message) } @@ -50,12 +50,12 @@ func Notify(event interface{}) { runtime.Notify("Event", event) } -// Verify method is used when contract is being used as a signer of transaction, +// Verify method is used when the contract is being used as a signer of transaction, // it can have parameters (that then need to be present in invocation script) // and it returns simple pass/fail result. This implementation just checks for -// owner's signature presence. +// the owner's signature presence. func Verify() bool { - // Technically this restriction is not needed, but you can see the difference + // Technically, this restriction is not needed, but you can see the difference // between invokefunction and invokecontractverify RPC methods with it. if runtime.GetTrigger() != runtime.Verification { return false @@ -63,7 +63,7 @@ func Verify() bool { return CheckWitness() } -// Destroy destroys the contract, only owner can do that. +// Destroy destroys the contract, only the owner can do that. func Destroy() { if !Verify() { panic("only owner can destroy") @@ -71,7 +71,7 @@ func Destroy() { management.Destroy() } -// Update updates the contract, only owner can do that. _deploy will be called +// Update updates the contract, only the owner can do that. _deploy will be called // after update. func Update(nef, manifest []byte) { if !Verify() { diff --git a/examples/storage/storage.go b/examples/storage/storage.go index 306e986bc..7f7c1c267 100644 --- a/examples/storage/storage.go +++ b/examples/storage/storage.go @@ -16,19 +16,19 @@ func init() { ctx = storage.GetContext() } -// Put puts value at key. +// Put puts the value at the key. func Put(key, value []byte) []byte { storage.Put(ctx, key, value) return key } -// PutDefault puts value to the default key. +// PutDefault puts the value to the default key. func PutDefault(value []byte) []byte { storage.Put(ctx, defaultKey, value) return defaultKey } -// Get returns the value at passed key. +// Get returns the value at the passed key. func Get(key []byte) interface{} { return storage.Get(ctx, key) } @@ -38,13 +38,13 @@ func GetDefault() interface{} { return storage.Get(ctx, defaultKey) } -// Delete deletes the value at passed key. +// Delete deletes the value at the passed key. func Delete(key []byte) bool { storage.Delete(ctx, key) return true } -// Find returns an array of key-value pairs with key that matched the passed value +// Find returns an array of key-value pairs with the key that matches the passed value. func Find(value []byte) []string { iter := storage.Find(ctx, value, storage.None) result := []string{} diff --git a/examples/token/token.go b/examples/token/token.go index 889dc8612..7cede5d3f 100644 --- a/examples/token/token.go +++ b/examples/token/token.go @@ -18,7 +18,7 @@ var ( ctx storage.Context ) -// init initializes the Token Interface and storage context for the Smart +// init initializes Token Interface and storage context for the Smart // Contract to operate with func init() { token = nep17.Token{ diff --git a/internal/contracts/contracts.go b/internal/contracts/contracts.go index d922985ff..dc381d5c6 100644 --- a/internal/contracts/contracts.go +++ b/internal/contracts/contracts.go @@ -26,7 +26,7 @@ var ( ) // GetTestContractState reads 2 pre-compiled contracts generated by -// TestGenerateHelperContracts second of which is allowed to call the first. +// TestGenerateHelperContracts, second of which is allowed to call the first. func GetTestContractState(t *testing.T, pathToInternalContracts string, id1, id2 int32, sender2 util.Uint160) (*state.Contract, *state.Contract) { errNotFound := errors.New("auto-generated oracle contract is not found, use TestGenerateHelperContracts to regenerate") neBytes, err := os.ReadFile(filepath.Join(pathToInternalContracts, helper1ContractNEFPath)) diff --git a/internal/contracts/contracts_test.go b/internal/contracts/contracts_test.go index 9b6fea22d..df9b4e80f 100644 --- a/internal/contracts/contracts_test.go +++ b/internal/contracts/contracts_test.go @@ -36,9 +36,9 @@ func TestGenerateHelperContracts(t *testing.T) { require.False(t, saveState) } -// generateOracleContract generates helper contract that is able to call -// native Oracle contract and has callback method. It uses test chain to define -// Oracle and StdLib native hashes and saves generated NEF and manifest to `oracle_contract` folder. +// generateOracleContract generates a helper contract that is able to call +// the native Oracle contract and has callback method. It uses testchain to define +// Oracle and StdLib native hashes and saves the generated NEF and manifest to `oracle_contract` folder. // Set `saveState` flag to true and run the test to rewrite NEF and manifest files. func generateOracleContract(t *testing.T, saveState bool) { bc, validator, committee := chain.NewMultiWithCustomConfig(t, func(c *config.ProtocolConfiguration) { @@ -131,9 +131,9 @@ func generateOracleContract(t *testing.T, saveState bool) { } } -// generateManagementHelperContracts generates 2 helper contracts second of which is -// allowed to call the first. It uses test chain to define Management and StdLib -// native hashes and saves generated NEF and manifest to `management_contract` folder. +// generateManagementHelperContracts generates 2 helper contracts, second of which is +// allowed to call the first. It uses testchain to define Management and StdLib +// native hashes and saves the generated NEF and manifest to `management_contract` folder. // Set `saveState` flag to true and run the test to rewrite NEF and manifest files. func generateManagementHelperContracts(t *testing.T, saveState bool) { bc, validator, committee := chain.NewMultiWithCustomConfig(t, func(c *config.ProtocolConfiguration) { diff --git a/internal/fakechain/fakechain.go b/internal/fakechain/fakechain.go index c781cbe59..9674034c9 100644 --- a/internal/fakechain/fakechain.go +++ b/internal/fakechain/fakechain.go @@ -25,7 +25,7 @@ import ( uatomic "go.uber.org/atomic" ) -// FakeChain implements Blockchainer interface, but does not provide real functionality. +// FakeChain implements the Blockchainer interface, but does not provide real functionality. type FakeChain struct { config.ProtocolConfiguration *mempool.Pool @@ -44,7 +44,7 @@ type FakeChain struct { UtilityTokenBalance *big.Int } -// FakeStateSync implements StateSync interface. +// FakeStateSync implements the StateSync interface. type FakeStateSync struct { IsActiveFlag uatomic.Bool IsInitializedFlag uatomic.Bool @@ -54,12 +54,12 @@ type FakeStateSync struct { AddMPTNodesFunc func(nodes [][]byte) error } -// NewFakeChain returns new FakeChain structure. +// NewFakeChain returns a new FakeChain structure. func NewFakeChain() *FakeChain { return NewFakeChainWithCustomCfg(nil) } -// NewFakeChainWithCustomCfg returns new FakeChain structure with specified protocol configuration. +// NewFakeChainWithCustomCfg returns a new FakeChain structure with the specified protocol configuration. func NewFakeChainWithCustomCfg(protocolCfg func(c *config.ProtocolConfiguration)) *FakeChain { cfg := config.ProtocolConfiguration{Magic: netmode.UnitTestNet, P2PNotaryRequestPayloadPoolSize: 10} if protocolCfg != nil { @@ -76,29 +76,29 @@ func NewFakeChainWithCustomCfg(protocolCfg func(c *config.ProtocolConfiguration) } } -// PutBlock implements Blockchainer interface. +// PutBlock implements the Blockchainer interface. func (chain *FakeChain) PutBlock(b *block.Block) { chain.blocks[b.Hash()] = b chain.hdrHashes[b.Index] = b.Hash() atomic.StoreUint32(&chain.Blockheight, b.Index) } -// PutHeader implements Blockchainer interface. +// PutHeader implements the Blockchainer interface. func (chain *FakeChain) PutHeader(b *block.Block) { chain.hdrHashes[b.Index] = b.Hash() } -// PutTx implements Blockchainer interface. +// PutTx implements the Blockchainer interface. func (chain *FakeChain) PutTx(tx *transaction.Transaction) { chain.txs[tx.Hash()] = tx } -// ApplyPolicyToTxSet implements Blockchainer interface. +// ApplyPolicyToTxSet implements the Blockchainer interface. func (chain *FakeChain) ApplyPolicyToTxSet([]*transaction.Transaction) []*transaction.Transaction { panic("TODO") } -// IsTxStillRelevant implements Blockchainer interface. +// IsTxStillRelevant implements the Blockchainer interface. func (chain *FakeChain) IsTxStillRelevant(t *transaction.Transaction, txpool *mempool.Pool, isPartialTx bool) bool { panic("TODO") } @@ -108,17 +108,17 @@ func (chain *FakeChain) InitVerificationContext(ic *interop.Context, hash util.U panic("TODO") } -// IsExtensibleAllowed implements Blockchainer interface. +// IsExtensibleAllowed implements the Blockchainer interface. func (*FakeChain) IsExtensibleAllowed(uint160 util.Uint160) bool { return true } -// GetNatives implements blockchainer.Blockchainer interface. +// GetNatives implements the blockchainer.Blockchainer interface. func (*FakeChain) GetNatives() []state.NativeContract { panic("TODO") } -// GetNotaryDepositExpiration implements Blockchainer interface. +// GetNotaryDepositExpiration implements the Blockchainer interface. func (chain *FakeChain) GetNotaryDepositExpiration(acc util.Uint160) uint32 { if chain.NotaryDepositExpiration != 0 { return chain.NotaryDepositExpiration @@ -126,7 +126,7 @@ func (chain *FakeChain) GetNotaryDepositExpiration(acc util.Uint160) uint32 { panic("TODO") } -// GetNotaryContractScriptHash implements Blockchainer interface. +// GetNotaryContractScriptHash implements the Blockchainer interface. func (chain *FakeChain) GetNotaryContractScriptHash() util.Uint160 { if !chain.NotaryContractScriptHash.Equals(util.Uint160{}) { return chain.NotaryContractScriptHash @@ -134,27 +134,27 @@ func (chain *FakeChain) GetNotaryContractScriptHash() util.Uint160 { panic("TODO") } -// GetNotaryBalance implements Blockchainer interface. +// GetNotaryBalance implements the Blockchainer interface. func (chain *FakeChain) GetNotaryBalance(acc util.Uint160) *big.Int { panic("TODO") } -// GetNotaryServiceFeePerKey implements Blockchainer interface. +// GetNotaryServiceFeePerKey implements the Blockchainer interface. func (chain *FakeChain) GetNotaryServiceFeePerKey() int64 { panic("TODO") } -// GetBaseExecFee implements Policer interface. +// GetBaseExecFee implements the Policer interface. func (chain *FakeChain) GetBaseExecFee() int64 { return interop.DefaultBaseExecFee } -// GetStoragePrice implements Policer interface. +// GetStoragePrice implements the Policer interface. func (chain *FakeChain) GetStoragePrice() int64 { return native.DefaultStoragePrice } -// GetMaxVerificationGAS implements Policer interface. +// GetMaxVerificationGAS implements the Policer interface. func (chain *FakeChain) GetMaxVerificationGAS() int64 { if chain.MaxVerificationGAS != 0 { return chain.MaxVerificationGAS @@ -162,22 +162,22 @@ func (chain *FakeChain) GetMaxVerificationGAS() int64 { panic("TODO") } -// PoolTxWithData implements Blockchainer interface. +// PoolTxWithData implements the Blockchainer interface. func (chain *FakeChain) PoolTxWithData(t *transaction.Transaction, data interface{}, mp *mempool.Pool, feer mempool.Feer, verificationFunction func(t *transaction.Transaction, data interface{}) error) error { return chain.poolTxWithData(t, data, mp) } -// RegisterPostBlock implements Blockchainer interface. +// RegisterPostBlock implements the Blockchainer interface. func (chain *FakeChain) RegisterPostBlock(f func(func(*transaction.Transaction, *mempool.Pool, bool) bool, *mempool.Pool, *block.Block)) { chain.PostBlock = append(chain.PostBlock, f) } -// GetConfig implements Blockchainer interface. +// GetConfig implements the Blockchainer interface. func (chain *FakeChain) GetConfig() config.ProtocolConfiguration { return chain.ProtocolConfiguration } -// CalculateClaimable implements Blockchainer interface. +// CalculateClaimable implements the Blockchainer interface. func (chain *FakeChain) CalculateClaimable(util.Uint160, uint32) (*big.Int, error) { panic("TODO") } @@ -192,12 +192,12 @@ func (chain *FakeChain) P2PSigExtensionsEnabled() bool { return true } -// AddHeaders implements Blockchainer interface. +// AddHeaders implements the Blockchainer interface. func (chain *FakeChain) AddHeaders(...*block.Header) error { panic("TODO") } -// AddBlock implements Blockchainer interface. +// AddBlock implements the Blockchainer interface. func (chain *FakeChain) AddBlock(block *block.Block) error { if block.Index == atomic.LoadUint32(&chain.Blockheight)+1 { chain.PutBlock(block) @@ -205,27 +205,27 @@ func (chain *FakeChain) AddBlock(block *block.Block) error { return nil } -// BlockHeight implements Feer interface. +// BlockHeight implements the Feer interface. func (chain *FakeChain) BlockHeight() uint32 { return atomic.LoadUint32(&chain.Blockheight) } -// Close implements Blockchainer interface. +// Close implements the Blockchainer interface. func (chain *FakeChain) Close() { panic("TODO") } -// HeaderHeight implements Blockchainer interface. +// HeaderHeight implements the Blockchainer interface. func (chain *FakeChain) HeaderHeight() uint32 { return atomic.LoadUint32(&chain.Blockheight) } -// GetAppExecResults implements Blockchainer interface. +// GetAppExecResults implements the Blockchainer interface. func (chain *FakeChain) GetAppExecResults(hash util.Uint256, trig trigger.Type) ([]state.AppExecResult, error) { panic("TODO") } -// GetBlock implements Blockchainer interface. +// GetBlock implements the Blockchainer interface. func (chain *FakeChain) GetBlock(hash util.Uint256) (*block.Block, error) { if b, ok := chain.blocks[hash]; ok { return b, nil @@ -233,27 +233,27 @@ func (chain *FakeChain) GetBlock(hash util.Uint256) (*block.Block, error) { return nil, errors.New("not found") } -// GetCommittee implements Blockchainer interface. +// GetCommittee implements the Blockchainer interface. func (chain *FakeChain) GetCommittee() (keys.PublicKeys, error) { panic("TODO") } -// GetContractState implements Blockchainer interface. +// GetContractState implements the Blockchainer interface. func (chain *FakeChain) GetContractState(hash util.Uint160) *state.Contract { panic("TODO") } -// GetContractScriptHash implements Blockchainer interface. +// GetContractScriptHash implements the Blockchainer interface. func (chain *FakeChain) GetContractScriptHash(id int32) (util.Uint160, error) { panic("TODO") } -// GetNativeContractScriptHash implements Blockchainer interface. +// GetNativeContractScriptHash implements the Blockchainer interface. func (chain *FakeChain) GetNativeContractScriptHash(name string) (util.Uint160, error) { panic("TODO") } -// GetHeaderHash implements Blockchainer interface. +// GetHeaderHash implements the Blockchainer interface. func (chain *FakeChain) GetHeaderHash(n int) util.Uint256 { if n < 0 || n > math.MaxUint32 { return util.Uint256{} @@ -261,7 +261,7 @@ func (chain *FakeChain) GetHeaderHash(n int) util.Uint256 { return chain.hdrHashes[uint32(n)] } -// GetHeader implements Blockchainer interface. +// GetHeader implements the Blockchainer interface. func (chain *FakeChain) GetHeader(hash util.Uint256) (*block.Header, error) { b, err := chain.GetBlock(hash) if err != nil { @@ -270,84 +270,84 @@ func (chain *FakeChain) GetHeader(hash util.Uint256) (*block.Header, error) { return &b.Header, nil } -// GetNextBlockValidators implements Blockchainer interface. +// GetNextBlockValidators implements the Blockchainer interface. func (chain *FakeChain) GetNextBlockValidators() ([]*keys.PublicKey, error) { panic("TODO") } -// GetNEP17Contracts implements Blockchainer interface. +// GetNEP17Contracts implements the Blockchainer interface. func (chain *FakeChain) GetNEP11Contracts() []util.Uint160 { panic("TODO") } -// GetNEP17Contracts implements Blockchainer interface. +// GetNEP17Contracts implements the Blockchainer interface. func (chain *FakeChain) GetNEP17Contracts() []util.Uint160 { panic("TODO") } -// GetNEP17LastUpdated implements Blockchainer interface. +// GetNEP17LastUpdated implements the Blockchainer interface. func (chain *FakeChain) GetTokenLastUpdated(acc util.Uint160) (map[int32]uint32, error) { panic("TODO") } -// ForEachNEP17Transfer implements Blockchainer interface. +// ForEachNEP17Transfer implements the Blockchainer interface. func (chain *FakeChain) ForEachNEP11Transfer(util.Uint160, uint64, func(*state.NEP11Transfer) (bool, error)) error { panic("TODO") } -// ForEachNEP17Transfer implements Blockchainer interface. +// ForEachNEP17Transfer implements the Blockchainer interface. func (chain *FakeChain) ForEachNEP17Transfer(util.Uint160, uint64, func(*state.NEP17Transfer) (bool, error)) error { panic("TODO") } -// GetValidators implements Blockchainer interface. +// GetValidators implements the Blockchainer interface. func (chain *FakeChain) GetValidators() ([]*keys.PublicKey, error) { panic("TODO") } -// GetEnrollments implements Blockchainer interface. +// GetEnrollments implements the Blockchainer interface. func (chain *FakeChain) GetEnrollments() ([]state.Validator, error) { panic("TODO") } -// GetStateModule implements Blockchainer interface. +// GetStateModule implements the Blockchainer interface. func (chain *FakeChain) GetStateModule() blockchainer.StateRoot { return nil } -// GetStorageItem implements Blockchainer interface. +// GetStorageItem implements the Blockchainer interface. func (chain *FakeChain) GetStorageItem(id int32, key []byte) state.StorageItem { panic("TODO") } -// GetTestVM implements Blockchainer interface. +// GetTestVM implements the Blockchainer interface. func (chain *FakeChain) GetTestVM(t trigger.Type, tx *transaction.Transaction, b *block.Block) *interop.Context { panic("TODO") } -// CurrentHeaderHash implements Blockchainer interface. +// CurrentHeaderHash implements the Blockchainer interface. func (chain *FakeChain) CurrentHeaderHash() util.Uint256 { return util.Uint256{} } -// CurrentBlockHash implements Blockchainer interface. +// CurrentBlockHash implements the Blockchainer interface. func (chain *FakeChain) CurrentBlockHash() util.Uint256 { return util.Uint256{} } -// HasBlock implements Blockchainer interface. +// HasBlock implements the Blockchainer interface. func (chain *FakeChain) HasBlock(h util.Uint256) bool { _, ok := chain.blocks[h] return ok } -// HasTransaction implements Blockchainer interface. +// HasTransaction implements the Blockchainer interface. func (chain *FakeChain) HasTransaction(h util.Uint256) bool { _, ok := chain.txs[h] return ok } -// GetTransaction implements Blockchainer interface. +// GetTransaction implements the Blockchainer interface. func (chain *FakeChain) GetTransaction(h util.Uint256) (*transaction.Transaction, uint32, error) { if tx, ok := chain.txs[h]; ok { return tx, 1, nil @@ -355,12 +355,12 @@ func (chain *FakeChain) GetTransaction(h util.Uint256) (*transaction.Transaction return nil, 0, errors.New("not found") } -// GetMemPool implements Blockchainer interface. +// GetMemPool implements the Blockchainer interface. func (chain *FakeChain) GetMemPool() *mempool.Pool { return chain.Pool } -// GetGoverningTokenBalance implements Blockchainer interface. +// GetGoverningTokenBalance implements the Blockchainer interface. func (chain *FakeChain) GetGoverningTokenBalance(acc util.Uint160) (*big.Int, uint32) { panic("TODO") } @@ -373,52 +373,52 @@ func (chain *FakeChain) GetUtilityTokenBalance(uint160 util.Uint160) *big.Int { panic("TODO") } -// ManagementContractHash implements Blockchainer interface. +// ManagementContractHash implements the Blockchainer interface. func (chain FakeChain) ManagementContractHash() util.Uint160 { panic("TODO") } -// PoolTx implements Blockchainer interface. +// PoolTx implements the Blockchainer interface. func (chain *FakeChain) PoolTx(tx *transaction.Transaction, _ ...*mempool.Pool) error { return chain.PoolTxF(tx) } -// SetOracle implements Blockchainer interface. +// SetOracle implements the Blockchainer interface. func (chain FakeChain) SetOracle(services.Oracle) { panic("TODO") } -// SetNotary implements Blockchainer interface. +// SetNotary implements the Blockchainer interface. func (chain *FakeChain) SetNotary(notary services.Notary) { panic("TODO") } -// SubscribeForBlocks implements Blockchainer interface. +// SubscribeForBlocks implements the Blockchainer interface. func (chain *FakeChain) SubscribeForBlocks(ch chan<- *block.Block) { chain.blocksCh = append(chain.blocksCh, ch) } -// SubscribeForExecutions implements Blockchainer interface. +// SubscribeForExecutions implements the Blockchainer interface. func (chain *FakeChain) SubscribeForExecutions(ch chan<- *state.AppExecResult) { panic("TODO") } -// SubscribeForNotifications implements Blockchainer interface. +// SubscribeForNotifications implements the Blockchainer interface. func (chain *FakeChain) SubscribeForNotifications(ch chan<- *subscriptions.NotificationEvent) { panic("TODO") } -// SubscribeForTransactions implements Blockchainer interface. +// SubscribeForTransactions implements the Blockchainer interface. func (chain *FakeChain) SubscribeForTransactions(ch chan<- *transaction.Transaction) { panic("TODO") } -// VerifyTx implements Blockchainer interface. +// VerifyTx implements the Blockchainer interface. func (chain *FakeChain) VerifyTx(*transaction.Transaction) error { panic("TODO") } -// VerifyWitness implements Blockchainer interface. +// VerifyWitness implements the Blockchainer interface. func (chain *FakeChain) VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) { if chain.VerifyWitnessF != nil { return chain.VerifyWitnessF() @@ -426,7 +426,7 @@ func (chain *FakeChain) VerifyWitness(util.Uint160, hash.Hashable, *transaction. panic("TODO") } -// UnsubscribeFromBlocks implements Blockchainer interface. +// UnsubscribeFromBlocks implements the Blockchainer interface. func (chain *FakeChain) UnsubscribeFromBlocks(ch chan<- *block.Block) { for i, c := range chain.blocksCh { if c == ch { @@ -438,32 +438,32 @@ func (chain *FakeChain) UnsubscribeFromBlocks(ch chan<- *block.Block) { } } -// UnsubscribeFromExecutions implements Blockchainer interface. +// UnsubscribeFromExecutions implements the Blockchainer interface. func (chain *FakeChain) UnsubscribeFromExecutions(ch chan<- *state.AppExecResult) { panic("TODO") } -// UnsubscribeFromNotifications implements Blockchainer interface. +// UnsubscribeFromNotifications implements the Blockchainer interface. func (chain *FakeChain) UnsubscribeFromNotifications(ch chan<- *subscriptions.NotificationEvent) { panic("TODO") } -// UnsubscribeFromTransactions implements Blockchainer interface. +// UnsubscribeFromTransactions implements the Blockchainer interface. func (chain *FakeChain) UnsubscribeFromTransactions(ch chan<- *transaction.Transaction) { panic("TODO") } -// AddBlock implements StateSync interface. +// AddBlock implements the StateSync interface. func (s *FakeStateSync) AddBlock(block *block.Block) error { panic("TODO") } -// AddHeaders implements StateSync interface. +// AddHeaders implements the StateSync interface. func (s *FakeStateSync) AddHeaders(...*block.Header) error { panic("TODO") } -// AddMPTNodes implements StateSync interface. +// AddMPTNodes implements the StateSync interface. func (s *FakeStateSync) AddMPTNodes(nodes [][]byte) error { if s.AddMPTNodesFunc != nil { return s.AddMPTNodesFunc(nodes) @@ -471,20 +471,20 @@ func (s *FakeStateSync) AddMPTNodes(nodes [][]byte) error { panic("TODO") } -// BlockHeight implements StateSync interface. +// BlockHeight implements the StateSync interface. func (s *FakeStateSync) BlockHeight() uint32 { return 0 } -// IsActive implements StateSync interface. +// IsActive implements the StateSync interface. func (s *FakeStateSync) IsActive() bool { return s.IsActiveFlag.Load() } -// IsInitialized implements StateSync interface. +// IsInitialized implements the StateSync interface. func (s *FakeStateSync) IsInitialized() bool { return s.IsInitializedFlag.Load() } -// Init implements StateSync interface. +// Init implements the StateSync interface. func (s *FakeStateSync) Init(currChainHeight uint32) error { if s.InitFunc != nil { return s.InitFunc(currChainHeight) @@ -492,15 +492,15 @@ func (s *FakeStateSync) Init(currChainHeight uint32) error { panic("TODO") } -// NeedHeaders implements StateSync interface. +// NeedHeaders implements the StateSync interface. func (s *FakeStateSync) NeedHeaders() bool { return s.RequestHeaders.Load() } -// NeedMPTNodes implements StateSync interface. +// NeedMPTNodes implements the StateSync interface. func (s *FakeStateSync) NeedMPTNodes() bool { panic("TODO") } -// Traverse implements StateSync interface. +// Traverse implements the StateSync interface. func (s *FakeStateSync) Traverse(root util.Uint256, process func(node mpt.Node, nodeBytes []byte) bool) error { if s.TraverseFunc != nil { return s.TraverseFunc(root, process) @@ -508,7 +508,7 @@ func (s *FakeStateSync) Traverse(root util.Uint256, process func(node mpt.Node, panic("TODO") } -// GetUnknownMPTNodesBatch implements StateSync interface. +// GetUnknownMPTNodesBatch implements the StateSync interface. func (s *FakeStateSync) GetUnknownMPTNodesBatch(limit int) []util.Uint256 { panic("TODO") } diff --git a/internal/testchain/address.go b/internal/testchain/address.go index 8e18f86a1..92aebb107 100644 --- a/internal/testchain/address.go +++ b/internal/testchain/address.go @@ -24,20 +24,20 @@ var privNetKeys = []string{ "KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY", "L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz", - // Provide 2 committee extra members so that committee address differs from + // Provide 2 committee extra members so that the committee address differs from // the validators one. "L1Tr1iq5oz1jaFaMXP21sHDkJYDDkuLtpvQ4wRf1cjKvJYvnvpAb", "Kz6XTUrExy78q8f4MjDHnwz8fYYyUE8iPXwPRAkHa3qN2JcHYm7e", } -// ValidatorsCount returns number of validators in the testchain. +// ValidatorsCount returns the number of validators in the testchain. const ValidatorsCount = 4 var ( // ids maps validators order by public key sorting to validators ID. - // which is an order of the validator in the StandByValidators list. + // That is the order of the validator in the StandByValidators list. ids = []int{1, 3, 0, 2, 4, 5} - // orders maps to validators id to it's order by public key sorting. + // orders maps validators id to its order by public key sorting. orders = []int{2, 0, 3, 1, 4, 5} ) @@ -56,12 +56,12 @@ func IDToOrder(id int) int { return orders[id] } -// WIF returns unencrypted wif of the specified validator. +// WIF returns the unencrypted wif of the specified validator. func WIF(i int) string { return privNetKeys[i] } -// PrivateKey returns private key of node #i. +// PrivateKey returns the private key of node #i. func PrivateKey(i int) *keys.PrivateKey { wif := WIF(i) priv, err := keys.NewPrivateKeyFromWIF(wif) @@ -154,7 +154,7 @@ func SignCommittee(h hash.Hashable) []byte { return buf.Bytes() } -// NewBlock creates new block for the given blockchain with the given offset +// NewBlock creates a new block for the given blockchain with the given offset // (usually, 1), primary node index and transactions. func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block { witness := transaction.Witness{VerificationScript: MultisigVerificationScript()} diff --git a/internal/testchain/network.go b/internal/testchain/network.go index 17863c1c4..d5702827e 100644 --- a/internal/testchain/network.go +++ b/internal/testchain/network.go @@ -2,7 +2,7 @@ package testchain import "github.com/nspcc-dev/neo-go/pkg/config/netmode" -// Network returns test chain network's magic number. +// Network returns testchain network's magic number. func Network() netmode.Magic { return netmode.UnitTestNet } diff --git a/internal/testchain/transaction.go b/internal/testchain/transaction.go index 7ce408ba1..387b7e6a9 100644 --- a/internal/testchain/transaction.go +++ b/internal/testchain/transaction.go @@ -28,7 +28,7 @@ var ( ownerScript = MultisigVerificationScript() ) -// NewTransferFromOwner returns transaction transferring funds from NEO and GAS owner. +// NewTransferFromOwner returns a transaction transferring funds from NEO and GAS owner. func NewTransferFromOwner(bc blockchainer.Blockchainer, contractHash, to util.Uint160, amount int64, nonce, validUntil uint32) (*transaction.Transaction, error) { w := io.NewBufBinWriter() @@ -51,8 +51,8 @@ func NewTransferFromOwner(bc blockchainer.Blockchainer, contractHash, to util.Ui return tx, SignTx(bc, tx) } -// NewDeployTx returns new deployment for contract with source from r and name equal to -// filename without '.go' suffix. +// NewDeployTx returns a new deployment transaction for a contract with the source from r and a name equal to +// the filename without '.go' suffix. func NewDeployTx(bc blockchainer.Blockchainer, name string, sender util.Uint160, r gio.Reader, confFile *string) (*transaction.Transaction, util.Uint160, []byte, error) { // nef.NewFile() cares about version a lot. config.Version = "0.90.0-test" @@ -110,7 +110,7 @@ func NewDeployTx(bc blockchainer.Blockchainer, name string, sender util.Uint160, return tx, h, ne.Script, nil } -// SignTx signs provided transactions with validator keys. +// SignTx signs the provided transactions with validator keys. func SignTx(bc blockchainer.Blockchainer, txs ...*transaction.Transaction) error { signTxGeneric(bc, Sign, ownerScript, txs...) return nil diff --git a/internal/testserdes/testing.go b/internal/testserdes/testing.go index d30e1ddaa..5bc7ad6d5 100644 --- a/internal/testserdes/testing.go +++ b/internal/testserdes/testing.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" ) -// MarshalUnmarshalJSON checks if expected stays the same after +// MarshalUnmarshalJSON checks if the expected stays the same after // marshal/unmarshal via JSON. func MarshalUnmarshalJSON(t *testing.T, expected, actual interface{}) { data, err := json.Marshal(expected) @@ -18,7 +18,7 @@ func MarshalUnmarshalJSON(t *testing.T, expected, actual interface{}) { require.Equal(t, expected, actual) } -// EncodeDecodeBinary checks if expected stays the same after +// EncodeDecodeBinary checks if the expected stays the same after // serializing/deserializing via io.Serializable methods. func EncodeDecodeBinary(t *testing.T, expected, actual io.Serializable) { data, err := EncodeBinary(expected) @@ -27,7 +27,7 @@ func EncodeDecodeBinary(t *testing.T, expected, actual io.Serializable) { require.Equal(t, expected, actual) } -// ToFromStackItem checks if expected stays the same after converting to/from +// ToFromStackItem checks if the expected stays the same after converting to/from // StackItem. func ToFromStackItem(t *testing.T, expected, actual stackitem.Convertible) { item, err := expected.ToStackItem() @@ -58,7 +58,7 @@ type encodable interface { Decode(*io.BinReader) error } -// EncodeDecode checks if expected stays the same after +// EncodeDecode checks if the expected stays the same after // serializing/deserializing via encodable methods. func EncodeDecode(t *testing.T, expected, actual encodable) { data, err := Encode(expected) diff --git a/pkg/compiler/analysis.go b/pkg/compiler/analysis.go index d9f494029..9e646e638 100644 --- a/pkg/compiler/analysis.go +++ b/pkg/compiler/analysis.go @@ -21,13 +21,13 @@ var ( } ) -// newGlobal creates new global variable. +// newGlobal creates a new global variable. func (c *codegen) newGlobal(pkg string, name string) { name = c.getIdentName(pkg, name) c.globals[name] = len(c.globals) } -// getIdentName returns fully-qualified name for a variable. +// getIdentName returns a fully-qualified name for a variable. func (c *codegen) getIdentName(pkg string, name string) string { if fullName, ok := c.importMap[pkg]; ok { pkg = fullName @@ -92,7 +92,7 @@ func (c *codegen) traverseGlobals() bool { } } // because we reuse `convertFuncDecl` for init funcs, - // we need to cleare scope, so that global variables + // we need to clear scope, so that global variables // encountered after will be recognized as globals. c.scope = nil }) @@ -133,7 +133,7 @@ func (c *codegen) traverseGlobals() bool { // countGlobals counts the global variables in the program to add // them with the stack size of the function. -// Second returned argument contains amount of global constants. +// Second returned argument contains the amount of global constants. func countGlobals(f ast.Node) (int, int) { var numVar, numConst int ast.Inspect(f, func(node ast.Node) bool { @@ -141,7 +141,7 @@ func countGlobals(f ast.Node) (int, int) { // Skip all function declarations if we have already encountered `defer`. case *ast.FuncDecl: return false - // After skipping all funcDecls we are sure that each value spec + // After skipping all funcDecls, we are sure that each value spec // is a global declared variable or constant. case *ast.GenDecl: isVar := n.Tok == token.VAR @@ -172,7 +172,7 @@ func isExprNil(e ast.Expr) bool { } // indexOfStruct returns the index of the given field inside that struct. -// If the struct does not contain that field it will return -1. +// If the struct does not contain that field, it will return -1. func indexOfStruct(strct *types.Struct, fldName string) int { for i := 0; i < strct.NumFields(); i++ { if strct.Field(i).Name() == fldName { @@ -189,7 +189,7 @@ func (f funcUsage) funcUsed(name string) bool { return ok } -// lastStmtIsReturn checks if last statement of the declaration was return statement.. +// lastStmtIsReturn checks if the last statement of the declaration was return statement. func lastStmtIsReturn(body *ast.BlockStmt) (b bool) { if l := len(body.List); l != 0 { switch inner := body.List[l-1].(type) { @@ -240,11 +240,11 @@ func (c *codegen) fillDocumentInfo() { }) } -// analyzeFuncUsage traverses all code and returns map with functions +// analyzeFuncUsage traverses all code and returns a map with functions // which should be present in the emitted code. // This is done using BFS starting from exported functions or -// function used in variable declarations (graph edge corresponds to -// function being called in declaration). +// the function used in variable declarations (graph edge corresponds to +// the function being called in declaration). func (c *codegen) analyzeFuncUsage() funcUsage { type declPair struct { decl *ast.FuncDecl @@ -376,8 +376,8 @@ func canConvert(s string) bool { return true } -// canInline returns true if function is to be inlined. -// Currently there is a static list of function which are inlined, +// canInline returns true if the function is to be inlined. +// Currently, there is a static list of functions which are inlined, // this may change in future. func canInline(s string, name string) bool { if strings.HasPrefix(s, "github.com/nspcc-dev/neo-go/pkg/compiler/testdata/inline") { diff --git a/pkg/compiler/codegen.go b/pkg/compiler/codegen.go index 88655b188..f1d86748a 100644 --- a/pkg/compiler/codegen.go +++ b/pkg/compiler/codegen.go @@ -35,7 +35,7 @@ type codegen struct { // Type information. typeInfo *types.Info - // pkgInfoInline is stack of type information for packages containing inline functions. + // pkgInfoInline is a stack of type information for packages containing inline functions. pkgInfoInline []*packages.Package // A mapping of func identifiers with their scope. @@ -63,9 +63,9 @@ type codegen struct { // A list of nested label names together with evaluation stack depth. labelList []labelWithStackSize // inlineLabelOffsets contains size of labelList at the start of inline call processing. - // For such calls we need to drop only newly created part of stack. + // For such calls, we need to drop only the newly created part of stack. inlineLabelOffsets []int - // globalInlineCount contains amount of auxiliary variables introduced by + // globalInlineCount contains the amount of auxiliary variables introduced by // function inlining during global variables initialization. globalInlineCount int @@ -76,7 +76,7 @@ type codegen struct { // A label to be used in the next statement. nextLabel string - // sequencePoints is mapping from method name to a slice + // sequencePoints is a mapping from the method name to a slice // containing info about mapping from opcode's offset // to a text span in the source file. sequencePoints map[string][]DebugSeqPoint @@ -92,25 +92,25 @@ type codegen struct { // constMap contains constants from foreign packages. constMap map[string]types.TypeAndValue - // currPkg is current package being processed. + // currPkg is the current package being processed. currPkg *packages.Package - // mainPkg is a main package metadata. + // mainPkg is the main package metadata. mainPkg *packages.Package // packages contains packages in the order they were loaded. packages []string packageCache map[string]*packages.Package - // exceptionIndex is the index of static slot where exception is stored. + // exceptionIndex is the index of the static slot where the exception is stored. exceptionIndex int // documents contains paths to all files used by the program. documents []string - // docIndex maps file path to an index in documents array. + // docIndex maps the file path to the index in the documents array. docIndex map[string]int - // emittedEvents contains all events emitted by contract. + // emittedEvents contains all events emitted by the contract. emittedEvents map[string][][]string // invokedContracts contains invoked methods of other contracts. @@ -166,7 +166,7 @@ func (c *codegen) newLabel() (l uint16) { return } -// newNamedLabel creates a new label with a specified name. +// newNamedLabel creates a new label with the specified name. func (c *codegen) newNamedLabel(typ labelOffsetType, name string) (l uint16) { l = c.newLabel() lt := labelWithType{name: name, typ: typ} @@ -223,8 +223,8 @@ func (c *codegen) emitStoreStructField(i int) { emit.Opcodes(c.prog.BinWriter, opcode.ROT, opcode.SETITEM) } -// getVarIndex returns variable type and position in corresponding slot, -// according to current scope. +// getVarIndex returns variable type and position in the corresponding slot, +// according to the current scope. func (c *codegen) getVarIndex(pkg string, name string) *varInfo { if pkg == "" { if c.scope != nil { @@ -255,7 +255,7 @@ func getBaseOpcode(t varType) (opcode.Opcode, opcode.Opcode) { } } -// emitLoadVar loads specified variable to the evaluation stack. +// emitLoadVar loads the specified variable to the evaluation stack. func (c *codegen) emitLoadVar(pkg string, name string) { vi := c.getVarIndex(pkg, name) if vi.ctx != nil && c.typeAndValueOf(vi.ctx.expr).Value != nil { @@ -284,7 +284,7 @@ func (c *codegen) emitLoadVar(pkg string, name string) { c.emitLoadByIndex(vi.refType, vi.index) } -// emitLoadByIndex loads specified variable type with index i. +// emitLoadByIndex loads the specified variable type with index i. func (c *codegen) emitLoadByIndex(t varType, i int) { base, _ := getBaseOpcode(t) if i < 7 { @@ -341,7 +341,7 @@ func (c *codegen) emitDefault(t types.Type) { } // convertGlobals traverses the AST and only converts global declarations. -// If we call this in convertFuncDecl then it will load all global variables +// If we call this in convertFuncDecl, it will load all global variables // into the scope of the function. func (c *codegen) convertGlobals(f *ast.File, _ *types.Package) { ast.Inspect(f, func(node ast.Node) bool { @@ -375,7 +375,7 @@ func (c *codegen) clearSlots(n int) { } // convertInitFuncs converts `init()` functions in file f and returns -// number of locals in last processed definition as well as maximum locals number encountered. +// the number of locals in the last processed definition as well as maximum locals number encountered. func (c *codegen) convertInitFuncs(f *ast.File, pkg *types.Package, lastCount int) (int, int) { maxCount := -1 ast.Inspect(f, func(node ast.Node) bool { @@ -479,10 +479,10 @@ func (c *codegen) convertFuncDecl(file ast.Node, decl *ast.FuncDecl, pkg *types. defer f.vars.dropScope() // We need to handle methods, which in Go, is just syntactic sugar. - // The method receiver will be passed in as first argument. - // We check if this declaration has a receiver and load it into scope. + // The method receiver will be passed in as the first argument. + // We check if this declaration has a receiver and load it into the scope. // - // FIXME: For now we will hard cast this to a struct. We can later fine tune this + // FIXME: For now, we will hard cast this to a struct. We can later fine tune this // to support other types. if decl.Recv != nil { for _, arg := range decl.Recv.List { @@ -915,12 +915,12 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { } case *ast.SelectorExpr: // If this is a method call we need to walk the AST to load the struct locally. - // Otherwise this is a function call from a imported package and we can call it + // Otherwise, this is a function call from an imported package and we can call it // directly. name, isMethod := c.getFuncNameFromSelector(fun) if isMethod { ast.Walk(c, fun.X) - // Dont forget to add 1 extra argument when its a method. + // Don't forget to add 1 extra argument when its a method. numArgs++ } @@ -983,7 +983,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { // We can be sure builtins are of type *ast.Ident. c.convertBuiltin(n) case name != "": - // Function was not found thus is can be only an invocation of func-typed variable or type conversion. + // Function was not found, thus it can only be an invocation of a func-typed variable or type conversion. // We care only about string conversions because all others are effectively no-op in NeoVM. // E.g. one cannot write `bool(int(a))`, only `int32(int(a))`. if isString(c.typeOf(n.Fun)) { @@ -1096,7 +1096,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { ast.Walk(c, n.X) c.emitToken(n.Tok, c.typeOf(n.X)) - // For now only identifiers are supported for (post) for stmts. + // For now, only identifiers are supported for (post) for stmts. // for i := 0; i < 10; i++ {} // Where the post stmt is ( i++ ) if ident, ok := n.X.(*ast.Ident); ok { @@ -1218,8 +1218,8 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { ast.Walk(c, n.X) // Implementation is a bit different for slices and maps: - // For slices we iterate index from 0 to len-1, storing array, len and index on stack. - // For maps we iterate index from 0 to len-1, storing map, keyarray, size and index on stack. + // For slices, we iterate through indices from 0 to len-1, storing array, len and index on stack. + // For maps, we iterate through indices from 0 to len-1, storing map, keyarray, size and index on stack. _, isMap := c.typeOf(n.X).Underlying().(*types.Map) emit.Opcodes(c.prog.BinWriter, opcode.DUP) if isMap { @@ -1281,10 +1281,10 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { return nil - // We dont really care about assertions for the core logic. + // We don't really care about assertions for the core logic. // The only thing we need is to please the compiler type checking. // For this to work properly, we only need to walk the expression - // not the assertion type. + // which is not the assertion type. case *ast.TypeAssertExpr: ast.Walk(c, n.X) if c.isCallExprSyscall(n.X) { @@ -1302,7 +1302,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor { } // packVarArgs packs variadic arguments into an array -// and returns amount of arguments packed. +// and returns the amount of arguments packed. func (c *codegen) packVarArgs(n *ast.CallExpr, typ *types.Signature) int { varSize := len(n.Args) - typ.Params().Len() + 1 c.emitReverse(varSize) @@ -1332,12 +1332,12 @@ func (c *codegen) isCallExprSyscall(e ast.Expr) bool { // Go `defer` statements are a bit different: // 1. `defer` is always executed irregardless of whether an exception has occurred. // 2. `recover` can or can not handle a possible exception. -// Thus we use the following approach: -// 1. Throwed exception is saved in a static field X, static fields Y and is set to true. +// Thus, we use the following approach: +// 1. Throwed exception is saved in a static field X, static fields Y and it is set to true. // 2. For each defer local there is a dedicated local variable which is set to 1 if `defer` statement // is encountered during an actual execution. // 3. CATCH and FINALLY blocks are the same, and both contain the same CALLs. -// 4. Right before the CATCH block check a variable from (2). If it is null, jump to the end of CATCH+FINALLY block. +// 4. Right before the CATCH block, check a variable from (2). If it is null, jump to the end of CATCH+FINALLY block. // 5. In CATCH block we set Y to true and emit default return values if it is the last defer. // 6. Execute FINALLY block only if Y is false. func (c *codegen) processDefers() { @@ -1386,7 +1386,7 @@ func (c *codegen) processDefers() { // emitExplicitConvert handles `someType(someValue)` conversions between string/[]byte. // Rules for conversion: // 1. interop.* types are converted to ByteArray if not already. -// 2. Otherwise convert between ByteArray/Buffer. +// 2. Otherwise, convert between ByteArray/Buffer. // 3. Rules for types which are not string/[]byte should already // be enforced by go parser. func (c *codegen) emitExplicitConvert(from, to types.Type) { @@ -1847,8 +1847,8 @@ func (c *codegen) convertBuiltin(expr *ast.CallExpr) { // There are special cases for builtins: // 1. With FromAddress, parameter conversion is happening at compile-time // so there is no need to push parameters on stack and perform an actual call -// 2. With panic, generated code depends on if argument was nil or a string so -// it should be handled accordingly. +// 2. With panic, the generated code depends on the fact if an argument was nil or a string; +// so, it should be handled accordingly. func transformArgs(fs *funcScope, fun ast.Expr, args []ast.Expr) []ast.Expr { switch f := fun.(type) { case *ast.SelectorExpr: @@ -1868,7 +1868,7 @@ func transformArgs(fs *funcScope, fun ast.Expr, args []ast.Expr) []ast.Expr { return args } -// emitConvert converts top stack item to the specified type. +// emitConvert converts the top stack item to the specified type. func (c *codegen) emitConvert(typ stackitem.Type) { emit.Opcodes(c.prog.BinWriter, opcode.DUP) emit.Instruction(c.prog.BinWriter, opcode.ISTYPE, []byte{byte(typ)}) @@ -2297,7 +2297,7 @@ func (c *codegen) replaceLabelWithOffset(ip int, arg []byte) (int, error) { // By pure coincidence, this is also the size of `INITSLOT` instruction. const longToShortRemoveCount = 3 -// shortenJumps returns converts b to a program where all long JMP*/CALL* specified by absolute offsets, +// shortenJumps converts b to a program where all long JMP*/CALL* specified by absolute offsets // are replaced with their corresponding short counterparts. It panics if either b or offsets are invalid. // This is done in 2 passes: // 1. Alter jump offsets taking into account parts to be removed. diff --git a/pkg/compiler/compiler.go b/pkg/compiler/compiler.go index e3f0cf45c..16c0fa114 100644 --- a/pkg/compiler/compiler.go +++ b/pkg/compiler/compiler.go @@ -24,7 +24,7 @@ import ( const fileExt = "nef" -// Options contains all the parameters that affect the behaviour of the compiler. +// Options contains all the parameters that affect the behavior of the compiler. type Options struct { // The extension of the output file default set to .nef Ext string @@ -51,10 +51,10 @@ type Options struct { // This setting has effect only if manifest is emitted. NoPermissionsCheck bool - // Name is contract's name to be written to manifest. + // Name is a contract's name to be written to manifest. Name string - // SourceURL is contract's source URL to be written to manifest. + // SourceURL is a contract's source URL to be written to manifest. SourceURL string // Runtime notifications. @@ -63,10 +63,10 @@ type Options struct { // The list of standards supported by the contract. ContractSupportedStandards []string - // SafeMethods contains list of methods which will be marked as safe in manifest. + // SafeMethods contains a list of methods which will be marked as safe in manifest. SafeMethods []string - // Overloads contains mapping from compiled method name to the name emitted in manifest. + // Overloads contains mapping from the compiled method name to the name emitted in manifest. // It can be used to provide method overloads as Go doesn't have such capability. Overloads map[string]string @@ -94,7 +94,7 @@ func (c *codegen) ForEachPackage(fn func(*packages.Package)) { } } -// ForEachFile executes fn on each file used in current program. +// ForEachFile executes fn on each file used in the current program. func (c *codegen) ForEachFile(fn func(*ast.File, *types.Package)) { c.ForEachPackage(func(pkg *packages.Package) { for _, f := range pkg.Syntax { @@ -173,7 +173,7 @@ func getBuildInfo(name string, src interface{}) (*buildInfo, error) { conf.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) { // When compiling a single file we can or can not load other files from the same package. - // Here we chose the latter which is consistent with `go run` behaviour. + // Here we chose the latter which is consistent with `go run` behavior. // Other dependencies should still be processed. if singleFile && filepath.Dir(filename) == filepath.Dir(absName) && filename != absName { return nil, nil @@ -196,9 +196,9 @@ func getBuildInfo(name string, src interface{}) (*buildInfo, error) { }, nil } -// Compile compiles a Go program into bytecode that can run on the NEO virtual machine. +// Compile compiles a Go program into a bytecode that can run on the NEO virtual machine. // If `r != nil`, `name` is interpreted as a filename, and `r` as file contents. -// Otherwise `name` is either file name or name of the directory containing source files. +// Otherwise `name` is either a file name or a name of the directory containing source files. func Compile(name string, r io.Reader) ([]byte, error) { f, _, err := CompileWithOptions(name, r, nil) if err != nil { @@ -208,7 +208,7 @@ func Compile(name string, r io.Reader) ([]byte, error) { return f.Script, nil } -// CompileWithOptions compiles a Go program into bytecode with provided compiler options. +// CompileWithOptions compiles a Go program into bytecode with the provided compiler options. func CompileWithOptions(name string, r io.Reader, o *Options) (*nef.File, *DebugInfo, error) { ctx, err := getBuildInfo(name, r) if err != nil { diff --git a/pkg/compiler/compiler_test.go b/pkg/compiler/compiler_test.go index 2390652b0..7dcd59786 100644 --- a/pkg/compiler/compiler_test.go +++ b/pkg/compiler/compiler_test.go @@ -28,7 +28,7 @@ type compilerTestCase struct { } func TestCompiler(t *testing.T) { - // CompileAndSave use config.Version for proper .nef generation. + // CompileAndSave uses config.Version for proper .nef generation. config.Version = "0.90.0-test" testCases := []compilerTestCase{ { @@ -53,7 +53,7 @@ func TestCompiler(t *testing.T) { for _, info := range infos { if !info.IsDir() { // example smart contracts are located in the `examplePath` subdirectories, but - // there are also a couple of files inside the `examplePath` which doesn't need to be compiled + // there is also a couple of files inside the `examplePath` which don't need to be compiled continue } diff --git a/pkg/compiler/debug.go b/pkg/compiler/debug.go index e6b16bcc5..8102ba7dc 100644 --- a/pkg/compiler/debug.go +++ b/pkg/compiler/debug.go @@ -31,7 +31,7 @@ type DebugInfo struct { EmittedEvents map[string][][]string `json:"-"` // InvokedContracts contains foreign contract invocations. InvokedContracts map[util.Uint160][]string `json:"-"` - // StaticVariables contains list of static variable names and types. + // StaticVariables contains a list of static variable names and types. StaticVariables []string `json:"static-variables"` } @@ -43,19 +43,19 @@ type MethodDebugInfo struct { // together with the namespace it belongs to. We need to keep the first letter // lowercased to match manifest standards. Name DebugMethodName `json:"name"` - // IsExported defines whether method is exported. + // IsExported defines whether the method is exported. IsExported bool `json:"-"` - // IsFunction defines whether method has no receiver. + // IsFunction defines whether the method has no receiver. IsFunction bool `json:"-"` // Range is the range of smart-contract's opcodes corresponding to the method. Range DebugRange `json:"range"` - // Parameters is a list of method's parameters. + // Parameters is a list of the method's parameters. Parameters []DebugParam `json:"params"` - // ReturnType is method's return type. + // ReturnType is the method's return type. ReturnType string `json:"return"` - // ReturnTypeReal is method's return type as specified in Go code. + // ReturnTypeReal is the method's return type as specified in Go code. ReturnTypeReal binding.Override `json:"-"` - // ReturnTypeSC is return type to use in manifest. + // ReturnTypeSC is a return type to use in manifest. ReturnTypeSC smartcontract.ParamType `json:"-"` Variables []string `json:"variables"` // SeqPoints is a map between source lines and byte-code instruction offsets. @@ -92,13 +92,13 @@ type DebugSeqPoint struct { EndCol int } -// DebugRange represents method's section in bytecode. +// DebugRange represents the method's section in bytecode. type DebugRange struct { Start uint16 End uint16 } -// DebugParam represents variables's name and type. +// DebugParam represents the variables's name and type. type DebugParam struct { Name string `json:"name"` Type string `json:"type"` @@ -362,13 +362,13 @@ func (c *codegen) scAndVMTypeFromType(t types.Type) (smartcontract.ParamType, st } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (d *DebugRange) MarshalJSON() ([]byte, error) { return []byte(`"` + strconv.FormatUint(uint64(d.Start), 10) + `-` + strconv.FormatUint(uint64(d.End), 10) + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (d *DebugRange) UnmarshalJSON(data []byte) error { startS, endS, err := parsePairJSON(data, "-") if err != nil { @@ -389,12 +389,12 @@ func (d *DebugRange) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (d *DebugParam) MarshalJSON() ([]byte, error) { return []byte(`"` + d.Name + `,` + d.Type + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (d *DebugParam) UnmarshalJSON(data []byte) error { startS, endS, err := parsePairJSON(data, ",") if err != nil { @@ -431,12 +431,12 @@ func (m *MethodDebugInfo) ToManifestMethod() manifest.Method { return result } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (d *DebugMethodName) MarshalJSON() ([]byte, error) { return []byte(`"` + d.Namespace + `,` + d.Name + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (d *DebugMethodName) UnmarshalJSON(data []byte) error { startS, endS, err := parsePairJSON(data, ",") if err != nil { @@ -449,14 +449,14 @@ func (d *DebugMethodName) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (d *DebugSeqPoint) MarshalJSON() ([]byte, error) { s := fmt.Sprintf("%d[%d]%d:%d-%d:%d", d.Opcode, d.Document, d.StartLine, d.StartCol, d.EndLine, d.EndCol) return []byte(`"` + s + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (d *DebugSeqPoint) UnmarshalJSON(data []byte) error { _, err := fmt.Sscanf(string(data), `"%d[%d]%d:%d-%d:%d"`, &d.Opcode, &d.Document, &d.StartLine, &d.StartCol, &d.EndLine, &d.EndCol) @@ -475,7 +475,7 @@ func parsePairJSON(data []byte, sep string) (string, string, error) { return ss[0], ss[1], nil } -// ConvertToManifest converts contract to the manifest.Manifest struct for debugger. +// ConvertToManifest converts a contract to the manifest.Manifest struct for debugger. // Note: manifest is taken from the external source, however it can be generated ad-hoc. See #1038. func (di *DebugInfo) ConvertToManifest(o *Options) (*manifest.Manifest, error) { methods := make([]manifest.Method, 0) diff --git a/pkg/compiler/func_scope.go b/pkg/compiler/func_scope.go index e9a5a7ef6..cf076ee76 100644 --- a/pkg/compiler/func_scope.go +++ b/pkg/compiler/func_scope.go @@ -6,7 +6,7 @@ import ( ) // A funcScope represents the scope within the function context. -// It holds al the local variables along with the initialized struct positions. +// It holds all the local variables along with the initialized struct positions. type funcScope struct { // Identifier of the function. name string diff --git a/pkg/compiler/syscall_test.go b/pkg/compiler/syscall_test.go index 479261744..68e948256 100644 --- a/pkg/compiler/syscall_test.go +++ b/pkg/compiler/syscall_test.go @@ -50,8 +50,8 @@ type syscallTestCase struct { isVoid bool } -// This test ensures that our wrappers have necessary number of parameters -// and execute needed syscall. Because of lack of typing (compared to native contracts) +// This test ensures that our wrappers have the necessary number of parameters +// and execute the appropriate syscall. Because of lack of typing (compared to native contracts), // parameter types can't be checked. func TestSyscallExecution(t *testing.T) { b := `[]byte{1}` diff --git a/pkg/compiler/verify_test.go b/pkg/compiler/verify_test.go index 408d82d9d..6bb54d4eb 100644 --- a/pkg/compiler/verify_test.go +++ b/pkg/compiler/verify_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -// In this test we only check that needed interop +// In this test, we only check that needed interop // is called with the provided arguments in the right order. func TestVerifyGood(t *testing.T) { msg := []byte("test message") diff --git a/pkg/config/config.go b/pkg/config/config.go index bbaaf2cd6..3e187f7bd 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -18,7 +18,7 @@ const ( UserAgentFormat = UserAgentWrapper + UserAgentPrefix + "%s" + UserAgentWrapper ) -// Version the version of the node, set at build time. +// Version is the version of the node, set at the build time. var Version string // Config top level struct representing the config @@ -28,7 +28,7 @@ type Config struct { ApplicationConfiguration ApplicationConfiguration `yaml:"ApplicationConfiguration"` } -// GenerateUserAgent creates user agent string based on build time environment. +// GenerateUserAgent creates a user agent string based on the build time environment. func (c Config) GenerateUserAgent() string { return fmt.Sprintf(UserAgentFormat, Version) } diff --git a/pkg/config/protocol_config.go b/pkg/config/protocol_config.go index c2f5dff01..d05802a17 100644 --- a/pkg/config/protocol_config.go +++ b/pkg/config/protocol_config.go @@ -28,7 +28,7 @@ type ( // P2PNotaryRequestPayloadPoolSize specifies the memory pool size for P2PNotaryRequestPayloads. // It is valid only if P2PSigExtensions are enabled. P2PNotaryRequestPayloadPoolSize int `yaml:"P2PNotaryRequestPayloadPoolSize"` - // KeepOnlyLatestState specifies if MPT should only store latest state. + // KeepOnlyLatestState specifies if MPT should only store the latest state. // If true, DB size will be smaller, but older roots won't be accessible. // This value should remain the same for the same database. KeepOnlyLatestState bool `yaml:"KeepOnlyLatestState"` @@ -46,7 +46,7 @@ type ( // exceeding that a transaction should fail validation. It is set to estimated daily number // of blocks with 15s interval. MaxValidUntilBlockIncrement uint32 `yaml:"MaxValidUntilBlockIncrement"` - // NativeUpdateHistories is the list of histories of native contracts updates. + // NativeUpdateHistories is a list of histories of native contracts updates. NativeUpdateHistories map[string][]uint32 `yaml:"NativeActivations"` // P2PSigExtensions enables additional signature-related logic. P2PSigExtensions bool `yaml:"P2PSigExtensions"` @@ -69,7 +69,7 @@ type ( ValidatorsHistory map[uint32]int `yaml:"ValidatorsHistory"` // Whether to verify received blocks. VerifyBlocks bool `yaml:"VerifyBlocks"` - // Whether to verify transactions in received blocks. + // Whether to verify transactions in the received blocks. VerifyTransactions bool `yaml:"VerifyTransactions"` } ) @@ -81,7 +81,7 @@ type heightNumber struct { } // Validate checks ProtocolConfiguration for internal consistency and returns -// error if anything inappropriate found. Other methods can rely on protocol +// an error if anything inappropriate found. Other methods can rely on protocol // validity after this. func (p *ProtocolConfiguration) Validate() error { var err error diff --git a/pkg/consensus/block.go b/pkg/consensus/block.go index fa40fe958..e52e7ef62 100644 --- a/pkg/consensus/block.go +++ b/pkg/consensus/block.go @@ -11,7 +11,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// neoBlock is a wrapper of core.Block which implements +// neoBlock is a wrapper of a core.Block which implements // methods necessary for dBFT library. type neoBlock struct { coreb.Block @@ -22,7 +22,7 @@ type neoBlock struct { var _ block.Block = (*neoBlock)(nil) -// Sign implements block.Block interface. +// Sign implements the block.Block interface. func (n *neoBlock) Sign(key crypto.PrivateKey) error { k := key.(*privateKey) sig := k.PrivateKey.SignHashable(uint32(n.network), &n.Block) @@ -30,7 +30,7 @@ func (n *neoBlock) Sign(key crypto.PrivateKey) error { return nil } -// Verify implements block.Block interface. +// Verify implements the block.Block interface. func (n *neoBlock) Verify(key crypto.PublicKey, sign []byte) error { k := key.(*publicKey) if k.PublicKey.VerifyHashable(sign, uint32(n.network), &n.Block) { @@ -39,7 +39,7 @@ func (n *neoBlock) Verify(key crypto.PublicKey, sign []byte) error { return errors.New("verification failed") } -// Transactions implements block.Block interface. +// Transactions implements the block.Block interface. func (n *neoBlock) Transactions() []block.Transaction { txes := make([]block.Transaction, len(n.Block.Transactions)) for i, tx := range n.Block.Transactions { @@ -49,7 +49,7 @@ func (n *neoBlock) Transactions() []block.Transaction { return txes } -// SetTransactions implements block.Block interface. +// SetTransactions implements the block.Block interface. func (n *neoBlock) SetTransactions(txes []block.Transaction) { n.Block.Transactions = make([]*transaction.Transaction, len(txes)) for i, tx := range txes { @@ -57,26 +57,26 @@ func (n *neoBlock) SetTransactions(txes []block.Transaction) { } } -// Version implements block.Block interface. +// Version implements the block.Block interface. func (n *neoBlock) Version() uint32 { return n.Block.Version } -// PrevHash implements block.Block interface. +// PrevHash implements the block.Block interface. func (n *neoBlock) PrevHash() util.Uint256 { return n.Block.PrevHash } -// MerkleRoot implements block.Block interface. +// MerkleRoot implements the block.Block interface. func (n *neoBlock) MerkleRoot() util.Uint256 { return n.Block.MerkleRoot } -// Timestamp implements block.Block interface. +// Timestamp implements the block.Block interface. func (n *neoBlock) Timestamp() uint64 { return n.Block.Timestamp * nsInMs } -// Index implements block.Block interface. +// Index implements the block.Block interface. func (n *neoBlock) Index() uint32 { return n.Block.Index } -// ConsensusData implements block.Block interface. +// ConsensusData implements the block.Block interface. func (n *neoBlock) ConsensusData() uint64 { return n.Block.Nonce } -// NextConsensus implements block.Block interface. +// NextConsensus implements the block.Block interface. func (n *neoBlock) NextConsensus() util.Uint160 { return n.Block.NextConsensus } -// Signature implements block.Block interface. +// Signature implements the block.Block interface. func (n *neoBlock) Signature() []byte { return n.signature } diff --git a/pkg/consensus/cache.go b/pkg/consensus/cache.go index 4a6853803..73a879fcc 100644 --- a/pkg/consensus/cache.go +++ b/pkg/consensus/cache.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// relayCache is a payload cache which is used to store +// relayCache is payload cache which is used to store // last consensus payloads. type relayCache struct { *sync.RWMutex @@ -17,7 +17,7 @@ type relayCache struct { queue *list.List } -// hashable is a type of items which can be stored in the relayCache. +// hashable is the type of items which can be stored in the relayCache. type hashable interface { Hash() util.Uint256 } @@ -32,7 +32,7 @@ func newFIFOCache(capacity int) *relayCache { } } -// Add adds payload into a cache if it doesn't already exist. +// Add adds payload into cache if it doesn't already exist there. func (c *relayCache) Add(p hashable) { c.Lock() defer c.Unlock() @@ -52,7 +52,7 @@ func (c *relayCache) Add(p hashable) { c.elems[h] = e } -// Has checks if an item is already in cache. +// Has checks if the item is already in cache. func (c *relayCache) Has(h util.Uint256) bool { c.RLock() defer c.RUnlock() diff --git a/pkg/consensus/change_view.go b/pkg/consensus/change_view.go index fedc72c8e..df796699a 100644 --- a/pkg/consensus/change_view.go +++ b/pkg/consensus/change_view.go @@ -14,32 +14,32 @@ type changeView struct { var _ payload.ChangeView = (*changeView)(nil) -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (c *changeView) EncodeBinary(w *io.BinWriter) { w.WriteU64LE(c.timestamp) w.WriteB(byte(c.reason)) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (c *changeView) DecodeBinary(r *io.BinReader) { c.timestamp = r.ReadU64LE() c.reason = payload.ChangeViewReason(r.ReadB()) } -// NewViewNumber implements payload.ChangeView interface. +// NewViewNumber implements the payload.ChangeView interface. func (c changeView) NewViewNumber() byte { return c.newViewNumber } -// SetNewViewNumber implements payload.ChangeView interface. +// SetNewViewNumber implements the payload.ChangeView interface. func (c *changeView) SetNewViewNumber(view byte) { c.newViewNumber = view } -// Timestamp implements payload.ChangeView interface. +// Timestamp implements the payload.ChangeView interface. func (c changeView) Timestamp() uint64 { return c.timestamp * nsInMs } -// SetTimestamp implements payload.ChangeView interface. +// SetTimestamp implements the payload.ChangeView interface. func (c *changeView) SetTimestamp(ts uint64) { c.timestamp = ts / nsInMs } -// Reason implements payload.ChangeView interface. +// Reason implements the payload.ChangeView interface. func (c changeView) Reason() payload.ChangeViewReason { return c.reason } -// SetReason implements payload.ChangeView interface. +// SetReason implements the payload.ChangeView interface. func (c *changeView) SetReason(reason payload.ChangeViewReason) { c.reason = reason } diff --git a/pkg/consensus/commit.go b/pkg/consensus/commit.go index 920d67745..a59a81183 100644 --- a/pkg/consensus/commit.go +++ b/pkg/consensus/commit.go @@ -11,25 +11,25 @@ type commit struct { } // signatureSize is an rfc6989 signature size in bytes -// without leading byte (0x04, uncompressed). +// without a leading byte (0x04, uncompressed). const signatureSize = 64 var _ payload.Commit = (*commit)(nil) -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (c *commit) EncodeBinary(w *io.BinWriter) { w.WriteBytes(c.signature[:]) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (c *commit) DecodeBinary(r *io.BinReader) { r.ReadBytes(c.signature[:]) } -// Signature implements payload.Commit interface. +// Signature implements the payload.Commit interface. func (c commit) Signature() []byte { return c.signature[:] } -// SetSignature implements payload.Commit interface. +// SetSignature implements the payload.Commit interface. func (c *commit) SetSignature(signature []byte) { copy(c.signature[:], signature) } diff --git a/pkg/consensus/consensus.go b/pkg/consensus/consensus.go index 28c9b4336..816d278f1 100644 --- a/pkg/consensus/consensus.go +++ b/pkg/consensus/consensus.go @@ -40,7 +40,7 @@ const defaultTimePerBlock = 15 * time.Second // Number of nanoseconds in millisecond. const nsInMs = 1000000 -// Category is message category for extensible payloads. +// Category is a message category for extensible payloads. const Category = "dBFT" // Ledger is the interface to Blockchain sufficient for Service. @@ -61,19 +61,19 @@ type Ledger interface { mempool.Feer } -// Service represents consensus instance. +// Service represents a consensus instance. type Service interface { // Name returns service name. Name() string // Start initializes dBFT and starts event loop for consensus service. - // It must be called only when sufficient amount of peers are connected. + // It must be called only when the sufficient amount of peers are connected. Start() // Shutdown stops dBFT event loop. Shutdown() - // OnPayload is a callback to notify Service about new received payload. + // OnPayload is a callback to notify the Service about a newly received payload. OnPayload(p *npayload.Extensible) error - // OnTransaction is a callback to notify Service about new received transaction. + // OnTransaction is a callback to notify the Service about a newly received transaction. OnTransaction(tx *transaction.Transaction) } @@ -100,8 +100,8 @@ type service struct { finished chan struct{} // lastTimestamp contains timestamp for the last processed block. // We can't rely on timestamp from dbft context because it is changed - // before block is accepted, so in case of change view it will contain - // updated value. + // before the block is accepted. So, in case of change view, it will contain + // an updated value. lastTimestamp uint64 } @@ -109,23 +109,23 @@ type service struct { type Config struct { // Logger is a logger instance. Logger *zap.Logger - // Broadcast is a callback which is called to notify server - // about new consensus payload to sent. + // Broadcast is a callback which is called to notify the server + // about a new consensus payload to be sent. Broadcast func(p *npayload.Extensible) // Chain is a Ledger instance. Chain Ledger // ProtocolConfiguration contains protocol settings. ProtocolConfiguration config.ProtocolConfiguration // RequestTx is a callback to which will be called - // when a node lacks transactions present in a block. + // when a node lacks transactions present in the block. RequestTx func(h ...util.Uint256) - // TimePerBlock minimal time that should pass before next block is accepted. + // TimePerBlock is minimal time that should pass before the next block is accepted. TimePerBlock time.Duration // Wallet is a local-node wallet configuration. Wallet *config.Wallet } -// NewService returns new consensus.Service instance. +// NewService returns a new consensus.Service instance. func NewService(cfg Config) (Service, error) { if cfg.TimePerBlock <= 0 { cfg.TimePerBlock = defaultTimePerBlock @@ -155,7 +155,7 @@ func NewService(cfg Config) (Service, error) { return nil, err } - // Check that wallet password is correct for at least one account. + // Check that the wallet password is correct for at least one account. var ok bool for _, acc := range srv.wallet.Accounts { err := acc.Decrypt(srv.Config.Wallet.Password, srv.wallet.Scrypt) @@ -213,7 +213,7 @@ var ( _ block.Block = (*neoBlock)(nil) ) -// NewPayload creates new consensus payload for the provided network. +// NewPayload creates a new consensus payload for the provided network. func NewPayload(m netmode.Magic, stateRootEnabled bool) *Payload { return &Payload{ Extensible: npayload.Extensible{ @@ -272,7 +272,7 @@ func (s *service) Start() { } } -// Shutdown implements Service interface. +// Shutdown implements the Service interface. func (s *service) Shutdown() { if s.started.Load() { close(s.quit) diff --git a/pkg/consensus/crypto.go b/pkg/consensus/crypto.go index 795a38797..0c6cc69b8 100644 --- a/pkg/consensus/crypto.go +++ b/pkg/consensus/crypto.go @@ -8,44 +8,44 @@ import ( ) // privateKey is a wrapper around keys.PrivateKey -// which implements crypto.PrivateKey interface. +// which implements the crypto.PrivateKey interface. type privateKey struct { *keys.PrivateKey } -// MarshalBinary implements encoding.BinaryMarshaler interface. +// MarshalBinary implements the encoding.BinaryMarshaler interface. func (p privateKey) MarshalBinary() (data []byte, err error) { return p.PrivateKey.Bytes(), nil } -// UnmarshalBinary implements encoding.BinaryUnmarshaler interface. +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. func (p *privateKey) UnmarshalBinary(data []byte) (err error) { p.PrivateKey, err = keys.NewPrivateKeyFromBytes(data) return } -// Sign implements dbft's crypto.PrivateKey interface. +// Sign implements the dbft's crypto.PrivateKey interface. func (p *privateKey) Sign(data []byte) ([]byte, error) { return p.PrivateKey.Sign(data), nil } // publicKey is a wrapper around keys.PublicKey -// which implements crypto.PublicKey interface. +// which implements the crypto.PublicKey interface. type publicKey struct { *keys.PublicKey } -// MarshalBinary implements encoding.BinaryMarshaler interface. +// MarshalBinary implements the encoding.BinaryMarshaler interface. func (p publicKey) MarshalBinary() (data []byte, err error) { return p.PublicKey.Bytes(), nil } -// UnmarshalBinary implements encoding.BinaryUnmarshaler interface. +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. func (p *publicKey) UnmarshalBinary(data []byte) error { return p.PublicKey.DecodeBytes(data) } -// Verify implements crypto.PublicKey interface. +// Verify implements the crypto.PublicKey interface. func (p publicKey) Verify(msg, sig []byte) error { hash := sha256.Sum256(msg) if p.PublicKey.Verify(sig, hash[:]) { diff --git a/pkg/consensus/payload.go b/pkg/consensus/payload.go index e4ae53066..d9290c49f 100644 --- a/pkg/consensus/payload.go +++ b/pkg/consensus/payload.go @@ -44,83 +44,83 @@ const ( payloadGasLimit = 2000000 // 0.02 GAS ) -// ViewNumber implements payload.ConsensusPayload interface. +// ViewNumber implements the payload.ConsensusPayload interface. func (p Payload) ViewNumber() byte { return p.message.ViewNumber } -// SetViewNumber implements payload.ConsensusPayload interface. +// SetViewNumber implements the payload.ConsensusPayload interface. func (p *Payload) SetViewNumber(view byte) { p.message.ViewNumber = view } -// Type implements payload.ConsensusPayload interface. +// Type implements the payload.ConsensusPayload interface. func (p Payload) Type() payload.MessageType { return payload.MessageType(p.message.Type) } -// SetType implements payload.ConsensusPayload interface. +// SetType implements the payload.ConsensusPayload interface. func (p *Payload) SetType(t payload.MessageType) { p.message.Type = messageType(t) } -// Payload implements payload.ConsensusPayload interface. +// Payload implements the payload.ConsensusPayload interface. func (p Payload) Payload() interface{} { return p.payload } -// SetPayload implements payload.ConsensusPayload interface. +// SetPayload implements the payload.ConsensusPayload interface. func (p *Payload) SetPayload(pl interface{}) { p.payload = pl.(io.Serializable) } -// GetChangeView implements payload.ConsensusPayload interface. +// GetChangeView implements the payload.ConsensusPayload interface. func (p Payload) GetChangeView() payload.ChangeView { return p.payload.(payload.ChangeView) } -// GetPrepareRequest implements payload.ConsensusPayload interface. +// GetPrepareRequest implements the payload.ConsensusPayload interface. func (p Payload) GetPrepareRequest() payload.PrepareRequest { return p.payload.(payload.PrepareRequest) } -// GetPrepareResponse implements payload.ConsensusPayload interface. +// GetPrepareResponse implements the payload.ConsensusPayload interface. func (p Payload) GetPrepareResponse() payload.PrepareResponse { return p.payload.(payload.PrepareResponse) } -// GetCommit implements payload.ConsensusPayload interface. +// GetCommit implements the payload.ConsensusPayload interface. func (p Payload) GetCommit() payload.Commit { return p.payload.(payload.Commit) } -// GetRecoveryRequest implements payload.ConsensusPayload interface. +// GetRecoveryRequest implements the payload.ConsensusPayload interface. func (p Payload) GetRecoveryRequest() payload.RecoveryRequest { return p.payload.(payload.RecoveryRequest) } -// GetRecoveryMessage implements payload.ConsensusPayload interface. +// GetRecoveryMessage implements the payload.ConsensusPayload interface. func (p Payload) GetRecoveryMessage() payload.RecoveryMessage { return p.payload.(payload.RecoveryMessage) } -// ValidatorIndex implements payload.ConsensusPayload interface. +// ValidatorIndex implements the payload.ConsensusPayload interface. func (p Payload) ValidatorIndex() uint16 { return uint16(p.message.ValidatorIndex) } -// SetValidatorIndex implements payload.ConsensusPayload interface. +// SetValidatorIndex implements the payload.ConsensusPayload interface. func (p *Payload) SetValidatorIndex(i uint16) { p.message.ValidatorIndex = byte(i) } -// Height implements payload.ConsensusPayload interface. +// Height implements the payload.ConsensusPayload interface. func (p Payload) Height() uint32 { return p.message.BlockIndex } -// SetHeight implements payload.ConsensusPayload interface. +// SetHeight implements the payload.ConsensusPayload interface. func (p *Payload) SetHeight(h uint32) { p.message.BlockIndex = h } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *Payload) EncodeBinary(w *io.BinWriter) { p.encodeData() p.Extensible.EncodeBinary(w) @@ -140,7 +140,7 @@ func (p *Payload) Sign(key *privateKey) error { return nil } -// Hash implements payload.ConsensusPayload interface. +// Hash implements the payload.ConsensusPayload interface. func (p *Payload) Hash() util.Uint256 { if p.Extensible.Data == nil { p.encodeData() @@ -148,7 +148,7 @@ func (p *Payload) Hash() util.Uint256 { return p.Extensible.Hash() } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *Payload) DecodeBinary(r *io.BinReader) { p.Extensible.DecodeBinary(r) if r.Err == nil { @@ -156,7 +156,7 @@ func (p *Payload) DecodeBinary(r *io.BinReader) { } } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (m *message) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(m.Type)) w.WriteU32LE(m.BlockIndex) @@ -165,7 +165,7 @@ func (m *message) EncodeBinary(w *io.BinWriter) { m.payload.EncodeBinary(w) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (m *message) DecodeBinary(r *io.BinReader) { m.Type = messageType(r.ReadB()) m.BlockIndex = r.ReadU32LE() diff --git a/pkg/consensus/prepare_request.go b/pkg/consensus/prepare_request.go index 4cbc61f04..3f883c1fd 100644 --- a/pkg/consensus/prepare_request.go +++ b/pkg/consensus/prepare_request.go @@ -20,7 +20,7 @@ type prepareRequest struct { var _ payload.PrepareRequest = (*prepareRequest)(nil) -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *prepareRequest) EncodeBinary(w *io.BinWriter) { w.WriteU32LE(p.version) w.WriteBytes(p.prevHash[:]) @@ -32,7 +32,7 @@ func (p *prepareRequest) EncodeBinary(w *io.BinWriter) { } } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *prepareRequest) DecodeBinary(r *io.BinReader) { p.version = r.ReadU32LE() r.ReadBytes(p.prevHash[:]) @@ -44,46 +44,46 @@ func (p *prepareRequest) DecodeBinary(r *io.BinReader) { } } -// Version implements payload.PrepareRequest interface. +// Version implements the payload.PrepareRequest interface. func (p prepareRequest) Version() uint32 { return p.version } -// SetVersion implements payload.PrepareRequest interface. +// SetVersion implements the payload.PrepareRequest interface. func (p *prepareRequest) SetVersion(v uint32) { p.version = v } -// PrevHash implements payload.PrepareRequest interface. +// PrevHash implements the payload.PrepareRequest interface. func (p prepareRequest) PrevHash() util.Uint256 { return p.prevHash } -// SetPrevHash implements payload.PrepareRequest interface. +// SetPrevHash implements the payload.PrepareRequest interface. func (p *prepareRequest) SetPrevHash(h util.Uint256) { p.prevHash = h } -// Timestamp implements payload.PrepareRequest interface. +// Timestamp implements the payload.PrepareRequest interface. func (p *prepareRequest) Timestamp() uint64 { return p.timestamp * nsInMs } -// SetTimestamp implements payload.PrepareRequest interface. +// SetTimestamp implements the payload.PrepareRequest interface. func (p *prepareRequest) SetTimestamp(ts uint64) { p.timestamp = ts / nsInMs } -// Nonce implements payload.PrepareRequest interface. +// Nonce implements the payload.PrepareRequest interface. func (p *prepareRequest) Nonce() uint64 { return p.nonce } -// SetNonce implements payload.PrepareRequest interface. +// SetNonce implements the payload.PrepareRequest interface. func (p *prepareRequest) SetNonce(nonce uint64) { p.nonce = nonce } -// TransactionHashes implements payload.PrepareRequest interface. +// TransactionHashes implements the payload.PrepareRequest interface. func (p *prepareRequest) TransactionHashes() []util.Uint256 { return p.transactionHashes } -// SetTransactionHashes implements payload.PrepareRequest interface. +// SetTransactionHashes implements the payload.PrepareRequest interface. func (p *prepareRequest) SetTransactionHashes(hs []util.Uint256) { p.transactionHashes = hs } -// NextConsensus implements payload.PrepareRequest interface. +// NextConsensus implements the payload.PrepareRequest interface. func (p *prepareRequest) NextConsensus() util.Uint160 { return util.Uint160{} } -// SetNextConsensus implements payload.PrepareRequest interface. +// SetNextConsensus implements the payload.PrepareRequest interface. func (p *prepareRequest) SetNextConsensus(_ util.Uint160) {} diff --git a/pkg/consensus/prepare_response.go b/pkg/consensus/prepare_response.go index 63b9bd98a..0fa93ab2d 100644 --- a/pkg/consensus/prepare_response.go +++ b/pkg/consensus/prepare_response.go @@ -13,18 +13,18 @@ type prepareResponse struct { var _ payload.PrepareResponse = (*prepareResponse)(nil) -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *prepareResponse) EncodeBinary(w *io.BinWriter) { w.WriteBytes(p.preparationHash[:]) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *prepareResponse) DecodeBinary(r *io.BinReader) { r.ReadBytes(p.preparationHash[:]) } -// PreparationHash implements payload.PrepareResponse interface. +// PreparationHash implements the payload.PrepareResponse interface. func (p *prepareResponse) PreparationHash() util.Uint256 { return p.preparationHash } -// SetPreparationHash implements payload.PrepareResponse interface. +// SetPreparationHash implements the payload.PrepareResponse interface. func (p *prepareResponse) SetPreparationHash(h util.Uint256) { p.preparationHash = h } diff --git a/pkg/consensus/recovery_message.go b/pkg/consensus/recovery_message.go index 6f8b66f2d..6ab826d7e 100644 --- a/pkg/consensus/recovery_message.go +++ b/pkg/consensus/recovery_message.go @@ -43,7 +43,7 @@ type ( var _ payload.RecoveryMessage = (*recoveryMessage)(nil) -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (m *recoveryMessage) DecodeBinary(r *io.BinReader) { r.ReadArray(&m.changeViewPayloads) @@ -73,7 +73,7 @@ func (m *recoveryMessage) DecodeBinary(r *io.BinReader) { r.ReadArray(&m.commitPayloads) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (m *recoveryMessage) EncodeBinary(w *io.BinWriter) { w.WriteArray(m.changeViewPayloads) @@ -94,7 +94,7 @@ func (m *recoveryMessage) EncodeBinary(w *io.BinWriter) { w.WriteArray(m.commitPayloads) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *changeViewCompact) DecodeBinary(r *io.BinReader) { p.ValidatorIndex = r.ReadB() p.OriginalViewNumber = r.ReadB() @@ -102,7 +102,7 @@ func (p *changeViewCompact) DecodeBinary(r *io.BinReader) { p.InvocationScript = r.ReadVarBytes(1024) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *changeViewCompact) EncodeBinary(w *io.BinWriter) { w.WriteB(p.ValidatorIndex) w.WriteB(p.OriginalViewNumber) @@ -110,7 +110,7 @@ func (p *changeViewCompact) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes(p.InvocationScript) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *commitCompact) DecodeBinary(r *io.BinReader) { p.ViewNumber = r.ReadB() p.ValidatorIndex = r.ReadB() @@ -118,7 +118,7 @@ func (p *commitCompact) DecodeBinary(r *io.BinReader) { p.InvocationScript = r.ReadVarBytes(1024) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *commitCompact) EncodeBinary(w *io.BinWriter) { w.WriteB(p.ViewNumber) w.WriteB(p.ValidatorIndex) @@ -126,19 +126,19 @@ func (p *commitCompact) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes(p.InvocationScript) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *preparationCompact) DecodeBinary(r *io.BinReader) { p.ValidatorIndex = r.ReadB() p.InvocationScript = r.ReadVarBytes(1024) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *preparationCompact) EncodeBinary(w *io.BinWriter) { w.WriteB(p.ValidatorIndex) w.WriteVarBytes(p.InvocationScript) } -// AddPayload implements payload.RecoveryMessage interface. +// AddPayload implements the payload.RecoveryMessage interface. func (m *recoveryMessage) AddPayload(p payload.ConsensusPayload) { validator := uint8(p.ValidatorIndex()) @@ -183,7 +183,7 @@ func (m *recoveryMessage) AddPayload(p payload.ConsensusPayload) { } } -// GetPrepareRequest implements payload.RecoveryMessage interface. +// GetPrepareRequest implements the payload.RecoveryMessage interface. func (m *recoveryMessage) GetPrepareRequest(p payload.ConsensusPayload, validators []crypto.PublicKey, primary uint16) payload.ConsensusPayload { if m.prepareRequest == nil { return nil @@ -210,7 +210,7 @@ func (m *recoveryMessage) GetPrepareRequest(p payload.ConsensusPayload, validato return req } -// GetPrepareResponses implements payload.RecoveryMessage interface. +// GetPrepareResponses implements the payload.RecoveryMessage interface. func (m *recoveryMessage) GetPrepareResponses(p payload.ConsensusPayload, validators []crypto.PublicKey) []payload.ConsensusPayload { if m.preparationHash == nil { return nil @@ -233,7 +233,7 @@ func (m *recoveryMessage) GetPrepareResponses(p payload.ConsensusPayload, valida return ps } -// GetChangeViews implements payload.RecoveryMessage interface. +// GetChangeViews implements the payload.RecoveryMessage interface. func (m *recoveryMessage) GetChangeViews(p payload.ConsensusPayload, validators []crypto.PublicKey) []payload.ConsensusPayload { ps := make([]payload.ConsensusPayload, len(m.changeViewPayloads)) @@ -254,7 +254,7 @@ func (m *recoveryMessage) GetChangeViews(p payload.ConsensusPayload, validators return ps } -// GetCommits implements payload.RecoveryMessage interface. +// GetCommits implements the payload.RecoveryMessage interface. func (m *recoveryMessage) GetCommits(p payload.ConsensusPayload, validators []crypto.PublicKey) []payload.ConsensusPayload { ps := make([]payload.ConsensusPayload, len(m.commitPayloads)) @@ -271,12 +271,12 @@ func (m *recoveryMessage) GetCommits(p payload.ConsensusPayload, validators []cr return ps } -// PreparationHash implements payload.RecoveryMessage interface. +// PreparationHash implements the payload.RecoveryMessage interface. func (m *recoveryMessage) PreparationHash() *util.Uint256 { return m.preparationHash } -// SetPreparationHash implements payload.RecoveryMessage interface. +// SetPreparationHash implements the payload.RecoveryMessage interface. func (m *recoveryMessage) SetPreparationHash(h *util.Uint256) { m.preparationHash = h } diff --git a/pkg/consensus/recovery_request.go b/pkg/consensus/recovery_request.go index 52e0fb269..6add949a5 100644 --- a/pkg/consensus/recovery_request.go +++ b/pkg/consensus/recovery_request.go @@ -12,18 +12,18 @@ type recoveryRequest struct { var _ payload.RecoveryRequest = (*recoveryRequest)(nil) -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (m *recoveryRequest) DecodeBinary(r *io.BinReader) { m.timestamp = r.ReadU64LE() } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (m *recoveryRequest) EncodeBinary(w *io.BinWriter) { w.WriteU64LE(m.timestamp) } -// Timestamp implements payload.RecoveryRequest interface. +// Timestamp implements the payload.RecoveryRequest interface. func (m *recoveryRequest) Timestamp() uint64 { return m.timestamp * nsInMs } -// SetTimestamp implements payload.RecoveryRequest interface. +// SetTimestamp implements the payload.RecoveryRequest interface. func (m *recoveryRequest) SetTimestamp(ts uint64) { m.timestamp = ts / nsInMs } diff --git a/pkg/core/block/block.go b/pkg/core/block/block.go index 97b041d0b..c9c50c70f 100644 --- a/pkg/core/block/block.go +++ b/pkg/core/block/block.go @@ -143,7 +143,7 @@ func (b *Block) EncodeBinary(bw *io.BinWriter) { } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (b Block) MarshalJSON() ([]byte, error) { auxb, err := json.Marshal(auxBlockOut{ Transactions: b.Transactions, @@ -165,7 +165,7 @@ func (b Block) MarshalJSON() ([]byte, error) { return baseBytes, nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (b *Block) UnmarshalJSON(data []byte) error { // As Base and auxb are at the same level in json, // do unmarshalling separately for both structs. @@ -192,7 +192,7 @@ func (b *Block) UnmarshalJSON(data []byte) error { return nil } -// GetExpectedBlockSize returns expected block size which should be equal to io.GetVarSize(b). +// GetExpectedBlockSize returns the expected block size which should be equal to io.GetVarSize(b). func (b *Block) GetExpectedBlockSize() int { var transactionsSize int for _, tx := range b.Transactions { @@ -201,7 +201,7 @@ func (b *Block) GetExpectedBlockSize() int { return b.GetExpectedBlockSizeWithoutTransactions(len(b.Transactions)) + transactionsSize } -// GetExpectedBlockSizeWithoutTransactions returns expected block size without transactions size. +// GetExpectedBlockSizeWithoutTransactions returns the expected block size without transactions size. func (b *Block) GetExpectedBlockSizeWithoutTransactions(txCount int) int { size := expectedHeaderSizeWithEmptyWitness - 1 - 1 + // 1 is for the zero-length (new(Header)).Script.Invocation/Verification io.GetVarSize(&b.Script) + diff --git a/pkg/core/block/block_test.go b/pkg/core/block/block_test.go index dd9df7ed1..bc437dbc1 100644 --- a/pkg/core/block/block_test.go +++ b/pkg/core/block/block_test.go @@ -23,7 +23,7 @@ func trim0x(value interface{}) string { return strings.TrimPrefix(s, "0x") } -// Test blocks are blocks from testnet with their corresponding index. +// Test blocks are blocks from testnet with their corresponding indices. func TestDecodeBlock1(t *testing.T) { data, err := getBlockData(1) require.NoError(t, err) @@ -126,12 +126,12 @@ func TestBinBlockDecodeEncode(t *testing.T) { assert.Equal(t, len(expected), len(hashes)) - // changes value in map to true, if hash found + // changes value in map to true, if hash is found for _, hash := range hashes { expected[hash] = true } - // iterate map; all vlaues should be true + // iterate map; all values should be true val := true for _, v := range expected { if v == false { @@ -151,7 +151,7 @@ func TestBlockSizeCalculation(t *testing.T) { // block taken from C# privnet: 02d7c7801742cd404eb178780c840477f1eef4a771ecc8cc9434640fe8f2bb09 // The Size in golang is given by counting the number of bytes of an object. (len(Bytes)) // its implementation is different from the corresponding C# and python implementations. But the result should - // should be the same.In this test we provide more details then necessary because in case of failure we can easily debug the + // be the same. In this test we provide more details then necessary because in case of failure we can easily debug the // root cause of the size calculation missmatch. rawBlock := "AAAAAAwIVa2D6Yha3tArd5XnwkAf7deJBsdyyvpYb2xMZGBbkOUNHAsfre0rKA/F+Ox05/bQSXmcRZnzK3M6Z+/TxJUh0MNFeAEAAAAAAAAAAAAAAQAAAADe7nnBifMAmLC6ai65CzqSWKbH/wHGDEDgwCcXkcaFw5MGOp1cpkgApzDTX2/RxKlmPeXTgWYtfEA8g9svUSbZA4TeoGyWvX8LiN0tJKrzajdMGvTVGqVmDEDp6PBmZmRx9CxswtLht6oWa2Uq4rl5diPsLtqXZeZepMlxUSbaCdlFTB7iWQG9yKXWR5hc0sScevvuVwwsUYdlDEDwlhwZrP07E5fEQKttVMYAiL7edd/eW2yoMGZe6Q95g7yXQ69edVHfQb61fBw3DjCpMDZ5lsxp3BgzXglJwMSKkxMMIQIQOn990BZVhZf3lg0nxRakOU/ZaLnmUVXrSwE+QEBAbgwhAqe8Vf6GhOARl2jRBLoweVvcyGYZ6GSt0mFWcj7Rhc1iDCECs2Ir9AF73+MXxYrtX0x1PyBrfbiWBG+n13S7xL9/jcIMIQPZDAffY+aQzneRLhCrUazJRLZoYCN7YIxPj4MJ5x7mmRRBe85spQIAWNC7C8DYpwAAAAAAIKpEAAAAAADoAwAAAd7uecGJ8wCYsLpqLrkLOpJYpsf/AQBbCwIA4fUFDBSAzse29bVvUFePc38WLTqxTUZlDQwU3u55wYnzAJiwumouuQs6klimx/8UwB8MCHRyYW5zZmVyDBT1Y+pAvCg9TQ4FxI6jBbPyoHNA70FifVtSOQHGDEC4UIzT61GYPx0LdksrF6C2ioYai6fbwpjv3BGAqiyagxiomYGZRLeXZyD67O5FJ86pXRFtSbVYu2YDG+T5ICIgDEDzm/wl+BnHvQXaHQ1rGLtdUMc41wN6I48kPPM7F23gL9sVxGziQIMRLnpTbWHrnzaU9Sy0fXkvIrdJy1KABkSQDEDBwuBuVK+nsZvn1oAscPj6d3FJiUGK9xiHpX9Ipp/5jTnXRBAyzyGc8IZMBVql4WS8kwFe6ojA/9BvFb5eWXnEkxMMIQIQOn990BZVhZf3lg0nxRakOU/ZaLnmUVXrSwE+QEBAbgwhAqe8Vf6GhOARl2jRBLoweVvcyGYZ6GSt0mFWcj7Rhc1iDCECs2Ir9AF73+MXxYrtX0x1PyBrfbiWBG+n13S7xL9/jcIMIQPZDAffY+aQzneRLhCrUazJRLZoYCN7YIxPj4MJ5x7mmRRBe85spQDYJLwZwNinAAAAAAAgqkQAAAAAAOgDAAAB3u55wYnzAJiwumouuQs6klimx/8BAF8LAwBA2d2ITQoADBSAzse29bVvUFePc38WLTqxTUZlDQwU3u55wYnzAJiwumouuQs6klimx/8UwB8MCHRyYW5zZmVyDBTPduKL0AYsSkeO41VhARMZ88+k0kFifVtSOQHGDEDWn0D7z2ELqpN8ghcM/PtfFwo56/BfEasfHuSKECJMYxvU47r2ZtSihg59lGxSZzHsvxTy6nsyvJ22ycNhINdJDECl61cg937N/HujKsLMu2wJMS7C54bzJ3q22Czqllvw3Yp809USgKDs+W+3QD7rI+SFs0OhIn0gooCUU6f/13WjDEDr9XdeT5CGTO8CL0JigzcTcucs0GBcqHs8fToO6zPuuCfS7Wh6dyxSCijT4A4S+7BUdW3dsO7828ke1fj8oNxmkxMMIQIQOn990BZVhZf3lg0nxRakOU/ZaLnmUVXrSwE+QEBAbgwhAqe8Vf6GhOARl2jRBLoweVvcyGYZ6GSt0mFWcj7Rhc1iDCECs2Ir9AF73+MXxYrtX0x1PyBrfbiWBG+n13S7xL9/jcIMIQPZDAffY+aQzneRLhCrUazJRLZoYCN7YIxPj4MJ5x7mmRRBe85spQ==" diff --git a/pkg/core/block/header.go b/pkg/core/block/header.go index 154d512d9..ba37658e9 100644 --- a/pkg/core/block/header.go +++ b/pkg/core/block/header.go @@ -25,8 +25,8 @@ type Header struct { MerkleRoot util.Uint256 // Timestamp is a millisecond-precision timestamp. - // The time stamp of each block must be later than previous block's time stamp. - // Generally the difference of two block's time stamp is about 15 seconds and imprecision is allowed. + // The time stamp of each block must be later than the previous block's time stamp. + // Generally, the difference between two block's time stamps is about 15 seconds and imprecision is allowed. // The height of the block must be exactly equal to the height of the previous block plus 1. Timestamp uint64 @@ -42,11 +42,11 @@ type Header struct { // Script used to validate the block Script transaction.Witness - // StateRootEnabled specifies if header contains state root. + // StateRootEnabled specifies if the header contains state root. StateRootEnabled bool - // PrevStateRoot is state root of the previous block. + // PrevStateRoot is the state root of the previous block. PrevStateRoot util.Uint256 - // PrimaryIndex is the index of primary consensus node for this block. + // PrimaryIndex is the index of the primary consensus node for this block. PrimaryIndex byte // Hash of this block, created when binary encoded (double SHA256). @@ -78,7 +78,7 @@ func (b *Header) Hash() util.Uint256 { return b.hash } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (b *Header) DecodeBinary(br *io.BinReader) { b.decodeHashableFields(br) witnessCount := br.ReadVarUint() @@ -90,7 +90,7 @@ func (b *Header) DecodeBinary(br *io.BinReader) { b.Script.DecodeBinary(br) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (b *Header) EncodeBinary(bw *io.BinWriter) { b.encodeHashableFields(bw) bw.WriteVarUint(1) @@ -98,11 +98,12 @@ func (b *Header) EncodeBinary(bw *io.BinWriter) { } // createHash creates the hash of the block. -// When calculating the hash value of the block, instead of calculating the entire block, -// only first seven fields in the block head will be calculated, which are -// version, PrevBlock, MerkleRoot, timestamp, and height, the nonce, NextMiner. -// Since MerkleRoot already contains the hash value of all transactions, -// the modification of transaction will influence the hash value of the block. +// When calculating the hash value of the block, instead of processing the entire block, +// only the header (without the signatures) is added as an input for the hash. It differs +// from the complete block only in that it doesn't contain transactions, but their hashes +// are used for MerkleRoot hash calculation. Therefore, adding/removing/changing any +// transaction affects the header hash and there is no need to use the complete block for +// hash calculation. func (b *Header) createHash() { buf := io.NewBufBinWriter() // No error can occur while encoding hashable fields. @@ -149,7 +150,7 @@ func (b *Header) decodeHashableFields(br *io.BinReader) { } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (b Header) MarshalJSON() ([]byte, error) { aux := baseAux{ Hash: b.Hash(), @@ -169,7 +170,7 @@ func (b Header) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (b *Header) UnmarshalJSON(data []byte) error { var aux = new(baseAux) var nextC util.Uint160 diff --git a/pkg/core/blockchain.go b/pkg/core/blockchain.go index 3776b4887..604fa2c62 100644 --- a/pkg/core/blockchain.go +++ b/pkg/core/blockchain.go @@ -439,7 +439,7 @@ func (bc *Blockchain) init() error { } // Check autogenerated native contracts' manifests and NEFs against the stored ones. - // Need to be done after native Management cache initialisation to be able to get + // Need to be done after native Management cache initialization to be able to get // contract state from DAO via high-level bc API. for _, c := range bc.contracts.Contracts { md := c.Metadata() diff --git a/pkg/core/blockchainer/blockchainer.go b/pkg/core/blockchainer/blockchainer.go index 6e7a1fcac..f8503d31f 100644 --- a/pkg/core/blockchainer/blockchainer.go +++ b/pkg/core/blockchainer/blockchainer.go @@ -17,7 +17,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// Blockchainer is an interface that abstract the implementation +// Blockchainer is an interface that abstracts the implementation // of the blockchain. type Blockchainer interface { ApplyPolicyToTxSet([]*transaction.Transaction) []*transaction.Transaction diff --git a/pkg/core/chaindump/dump.go b/pkg/core/chaindump/dump.go index 54ae5d514..d2cf45469 100644 --- a/pkg/core/chaindump/dump.go +++ b/pkg/core/chaindump/dump.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// DumperRestorer in the interface to get/add blocks from/to. +// DumperRestorer is an interface to get/add blocks from/to. type DumperRestorer interface { AddBlock(block *block.Block) error GetBlock(hash util.Uint256) (*block.Block, error) @@ -18,7 +18,7 @@ type DumperRestorer interface { } // Dump writes count blocks from start to the provided writer. -// Note: header needs to be written separately by client. +// Note: header needs to be written separately by a client. func Dump(bc DumperRestorer, w *io.BinWriter, start, count uint32) error { for i := start; i < start+count; i++ { bh := bc.GetHeaderHash(int(i)) @@ -38,7 +38,7 @@ func Dump(bc DumperRestorer, w *io.BinWriter, start, count uint32) error { return nil } -// Restore restores blocks from provided reader. +// Restore restores blocks from the provided reader. // f is called after addition of every block. func Restore(bc DumperRestorer, r *io.BinReader, skip, count uint32, f func(b *block.Block) error) error { readBlock := func(r *io.BinReader) ([]byte, error) { diff --git a/pkg/core/dao/dao.go b/pkg/core/dao/dao.go index af268e679..5620ad7c0 100644 --- a/pkg/core/dao/dao.go +++ b/pkg/core/dao/dao.go @@ -21,12 +21,12 @@ import ( // HasTransaction errors. var ( - // ErrAlreadyExists is returned when transaction exists in dao. + // ErrAlreadyExists is returned when the transaction exists in dao. ErrAlreadyExists = errors.New("transaction already exists") - // ErrHasConflicts is returned when transaction is in the list of conflicting + // ErrHasConflicts is returned when the transaction is in the list of conflicting // transactions which are already in dao. ErrHasConflicts = errors.New("transaction has conflicts") - // ErrInternalDBInconsistency is returned when the format of retrieved DAO + // ErrInternalDBInconsistency is returned when the format of the retrieved DAO // record is unexpected. ErrInternalDBInconsistency = errors.New("internal DB inconsistency") ) @@ -57,7 +57,7 @@ type NativeContractCache interface { Copy() NativeContractCache } -// NewSimple creates new simple dao using provided backend store. +// NewSimple creates a new simple dao using the provided backend store. func NewSimple(backend storage.Store, stateRootInHeader bool, p2pSigExtensions bool) *Simple { st := storage.NewMemCachedStore(backend) return newSimple(st, stateRootInHeader, p2pSigExtensions) @@ -75,12 +75,12 @@ func newSimple(st *storage.MemCachedStore, stateRootInHeader bool, p2pSigExtensi } } -// GetBatch returns currently accumulated DB changeset. +// GetBatch returns the currently accumulated DB changeset. func (dao *Simple) GetBatch() *storage.MemBatch { return dao.Store.GetBatch() } -// GetWrapped returns new DAO instance with another layer of wrapped +// GetWrapped returns a new DAO instance with another layer of wrapped // MemCachedStore around the current DAO Store. func (dao *Simple) GetWrapped() *Simple { d := NewSimple(dao.Store, dao.Version.StateRootInHeader, dao.Version.P2PSigExtensions) @@ -89,7 +89,7 @@ func (dao *Simple) GetWrapped() *Simple { return d } -// GetPrivate returns new DAO instance with another layer of private +// GetPrivate returns a new DAO instance with another layer of private // MemCachedStore around the current DAO Store. func (dao *Simple) GetPrivate() *Simple { d := &Simple{ @@ -142,12 +142,12 @@ func (dao *Simple) DeleteContractID(id int32) { dao.Store.Delete(dao.makeContractIDKey(id)) } -// PutContractID adds a mapping from contract's ID to its hash. +// PutContractID adds a mapping from a contract's ID to its hash. func (dao *Simple) PutContractID(id int32, hash util.Uint160) { dao.Store.Put(dao.makeContractIDKey(id), hash.BytesBE()) } -// GetContractScriptHash retrieves contract's hash given its ID. +// GetContractScriptHash retrieves the contract's hash given its ID. func (dao *Simple) GetContractScriptHash(id int32) (util.Uint160, error) { var data = new(util.Uint160) if err := dao.GetAndDecode(data, dao.makeContractIDKey(id)); err != nil { @@ -259,7 +259,7 @@ func (dao *Simple) GetTokenTransferLog(acc util.Uint160, newestTimestamp uint64, return &state.TokenTransferLog{Raw: value}, nil } -// PutTokenTransferLog saves given transfer log in the cache. +// PutTokenTransferLog saves the given transfer log in the cache. func (dao *Simple) PutTokenTransferLog(acc util.Uint160, start uint64, index uint32, isNEP11 bool, lg *state.TokenTransferLog) { key := dao.getTokenTransferLogKey(acc, start, index, isNEP11) dao.Store.Put(key, lg.Raw) @@ -377,22 +377,22 @@ func (dao *Simple) GetStorageItem(id int32, key []byte) state.StorageItem { return b } -// PutStorageItem puts given StorageItem for given id with given +// PutStorageItem puts the given StorageItem for the given id with the given // key into the given store. func (dao *Simple) PutStorageItem(id int32, key []byte, si state.StorageItem) { stKey := dao.makeStorageItemKey(id, key) dao.Store.Put(stKey, si) } -// DeleteStorageItem drops storage item for the given id with the +// DeleteStorageItem drops a storage item for the given id with the // given key from the store. func (dao *Simple) DeleteStorageItem(id int32, key []byte) { stKey := dao.makeStorageItemKey(id, key) dao.Store.Delete(stKey) } -// Seek executes f for all storage items matching a given `rng` (matching given prefix and -// starting from the point specified). If key or value is to be used outside of f, they +// Seek executes f for all storage items matching the given `rng` (matching the given prefix and +// starting from the point specified). If the key or the value is to be used outside of f, they // may not be copied. Seek continues iterating until false is returned from f. func (dao *Simple) Seek(id int32, rng storage.SeekRange, f func(k, v []byte) bool) { rng.Prefix = slice.Copy(dao.makeStorageItemKey(id, rng.Prefix)) // f() can use dao too. @@ -401,7 +401,7 @@ func (dao *Simple) Seek(id int32, rng storage.SeekRange, f func(k, v []byte) boo }) } -// SeekAsync sends all storage items matching a given `rng` (matching given prefix and +// SeekAsync sends all storage items matching the given `rng` (matching the given prefix and // starting from the point specified) to a channel and returns the channel. // Resulting keys and values may not be copied. func (dao *Simple) SeekAsync(ctx context.Context, id int32, rng storage.SeekRange) chan storage.KeyValue { @@ -409,7 +409,7 @@ func (dao *Simple) SeekAsync(ctx context.Context, id int32, rng storage.SeekRang return dao.Store.SeekAsync(ctx, rng, true) } -// makeStorageItemKey returns a key used to store StorageItem in the DB. +// makeStorageItemKey returns the key used to store the StorageItem in the DB. func (dao *Simple) makeStorageItemKey(id int32, key []byte) []byte { // 1 for prefix + 4 for Uint32 + len(key) for key buf := dao.getKeyBuf(5 + len(key)) @@ -446,7 +446,7 @@ func (dao *Simple) getBlock(key []byte) (*block.Block, error) { return block, nil } -// Version represents current dao version. +// Version represents the current dao version. type Version struct { StoragePrefix storage.KeyPrefix StateRootInHeader bool @@ -549,7 +549,7 @@ func (dao *Simple) GetCurrentHeaderHeight() (i uint32, h util.Uint256, err error return } -// GetStateSyncPoint returns current state synchronisation point P. +// GetStateSyncPoint returns current state synchronization point P. func (dao *Simple) GetStateSyncPoint() (uint32, error) { b, err := dao.Store.Get(dao.mkKeyPrefix(storage.SYSStateSyncPoint)) if err != nil { @@ -558,8 +558,8 @@ func (dao *Simple) GetStateSyncPoint() (uint32, error) { return binary.LittleEndian.Uint32(b), nil } -// GetStateSyncCurrentBlockHeight returns current block height stored during state -// synchronisation process. +// GetStateSyncCurrentBlockHeight returns the current block height stored during state +// synchronization process. func (dao *Simple) GetStateSyncCurrentBlockHeight() (uint32, error) { b, err := dao.Store.Get(dao.mkKeyPrefix(storage.SYSStateSyncCurrentBlockHeight)) if err != nil { @@ -627,7 +627,7 @@ func (dao *Simple) PutVersion(v Version) { dao.Store.Put(dao.mkKeyPrefix(storage.SYSVersion), v.Bytes()) } -// PutCurrentHeader stores current header. +// PutCurrentHeader stores the current header. func (dao *Simple) PutCurrentHeader(h util.Uint256, index uint32) { buf := dao.getDataBuf() buf.WriteBytes(h.BytesLE()) @@ -635,14 +635,14 @@ func (dao *Simple) PutCurrentHeader(h util.Uint256, index uint32) { dao.Store.Put(dao.mkKeyPrefix(storage.SYSCurrentHeader), buf.Bytes()) } -// PutStateSyncPoint stores current state synchronisation point P. +// PutStateSyncPoint stores the current state synchronization point P. func (dao *Simple) PutStateSyncPoint(p uint32) { buf := dao.getDataBuf() buf.WriteU32LE(p) dao.Store.Put(dao.mkKeyPrefix(storage.SYSStateSyncPoint), buf.Bytes()) } -// PutStateSyncCurrentBlockHeight stores current block height during state synchronisation process. +// PutStateSyncCurrentBlockHeight stores the current block height during state synchronization process. func (dao *Simple) PutStateSyncCurrentBlockHeight(h uint32) { buf := dao.getDataBuf() buf.WriteU32LE(h) @@ -682,7 +682,7 @@ func (dao *Simple) StoreHeaderHashes(hashes []util.Uint256, height uint32) error } // HasTransaction returns nil if the given store does not contain the given -// Transaction hash. It returns an error in case if transaction is in chain +// Transaction hash. It returns an error in case the transaction is in chain // or in the list of conflicting transactions. func (dao *Simple) HasTransaction(hash util.Uint256) error { key := dao.makeExecutableKey(hash) @@ -722,7 +722,7 @@ func (dao *Simple) StoreAsBlock(block *block.Block, aer1 *state.AppExecResult, a return nil } -// DeleteBlock removes block from dao. It's not atomic, so make sure you're +// DeleteBlock removes the block from dao. It's not atomic, so make sure you're // using private MemCached instance here. func (dao *Simple) DeleteBlock(h util.Uint256) error { key := dao.makeExecutableKey(h) @@ -752,7 +752,7 @@ func (dao *Simple) DeleteBlock(h util.Uint256) error { return nil } -// StoreHeader saves block header into the store. +// StoreHeader saves the block header into the store. func (dao *Simple) StoreHeader(h *block.Header) error { return dao.storeHeader(dao.makeExecutableKey(h.Hash()), h) } @@ -769,9 +769,8 @@ func (dao *Simple) storeHeader(key []byte, h *block.Header) error { return nil } -// StoreAsCurrentBlock stores a hash of the given block with prefix -// SYSCurrentBlock. It can reuse given buffer for the purpose of value -// serialization. +// StoreAsCurrentBlock stores the hash of the given block with prefix +// SYSCurrentBlock. func (dao *Simple) StoreAsCurrentBlock(block *block.Block) { buf := dao.getDataBuf() h := block.Hash() @@ -780,8 +779,8 @@ func (dao *Simple) StoreAsCurrentBlock(block *block.Block) { dao.Store.Put(dao.mkKeyPrefix(storage.SYSCurrentBlock), buf.Bytes()) } -// StoreAsTransaction stores given TX as DataTransaction. It also stores transactions -// given tx has conflicts with as DataTransaction with dummy version. It can reuse given +// StoreAsTransaction stores the given TX as DataTransaction. It also stores transactions +// the given tx has conflicts with as DataTransaction with dummy version. It can reuse the given // buffer for the purpose of value serialization. func (dao *Simple) StoreAsTransaction(tx *transaction.Transaction, index uint32, aer *state.AppExecResult) error { key := dao.makeExecutableKey(tx.Hash()) diff --git a/pkg/core/fee/calculate.go b/pkg/core/fee/calculate.go index 4942f3f89..ca64e5705 100644 --- a/pkg/core/fee/calculate.go +++ b/pkg/core/fee/calculate.go @@ -10,7 +10,7 @@ import ( // ECDSAVerifyPrice is a gas price of a single verification. const ECDSAVerifyPrice = 1 << 15 -// Calculate returns network fee for transaction. +// Calculate returns network fee for a transaction. func Calculate(base int64, script []byte) (int64, int) { var ( netFee int64 diff --git a/pkg/core/fee/opcode.go b/pkg/core/fee/opcode.go index 844ee0393..5499c9078 100644 --- a/pkg/core/fee/opcode.go +++ b/pkg/core/fee/opcode.go @@ -4,7 +4,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/opcode" ) -// Opcode returns the deployment coefficients of specified opcodes. +// Opcode returns the deployment coefficients of the specified opcodes. func Opcode(base int64, opcodes ...opcode.Opcode) int64 { var result int64 for _, op := range opcodes { diff --git a/pkg/core/fee/opcode_test.go b/pkg/core/fee/opcode_test.go index 39edf3e5b..292d95dc9 100644 --- a/pkg/core/fee/opcode_test.go +++ b/pkg/core/fee/opcode_test.go @@ -8,7 +8,7 @@ import ( const feeFactor = 30 -// The most common Opcode() use case is to get price for single opcode. +// The most common Opcode() use case is to get price for a single opcode. func BenchmarkOpcode1(t *testing.B) { // Just so that we don't always test the same opcode. script := []opcode.Opcode{opcode.NOP, opcode.ADD, opcode.SYSCALL, opcode.APPEND} diff --git a/pkg/core/interop/context.go b/pkg/core/interop/context.go index 351052918..5e7caf1fb 100644 --- a/pkg/core/interop/context.go +++ b/pkg/core/interop/context.go @@ -30,7 +30,7 @@ import ( ) const ( - // DefaultBaseExecFee specifies default multiplier for opcode and syscall prices. + // DefaultBaseExecFee specifies the default multiplier for opcode and syscall prices. DefaultBaseExecFee = 30 ) @@ -104,7 +104,7 @@ func (ic *Context) UseSigners(s []transaction.Signer) { ic.signers = s } -// Signers returns signers witnessing current execution context. +// Signers returns signers witnessing the current execution context. func (ic *Context) Signers() []transaction.Signer { if ic.signers != nil { return ic.signers @@ -115,7 +115,7 @@ func (ic *Context) Signers() []transaction.Signer { return nil } -// Function binds function name, id with the function itself and price, +// Function binds function name, id with the function itself and the price, // it's supposed to be inited once for all interopContexts, so it doesn't use // vm.InteropFuncPrice directly. type Function struct { @@ -151,7 +151,7 @@ type Contract interface { PostPersist(*Context) error } -// ContractMD represents native contract instance. +// ContractMD represents a native contract instance. type ContractMD struct { state.NativeContract Name string @@ -164,8 +164,8 @@ func NewContractMD(name string, id int32) *ContractMD { c.ID = id - // NEF is now stored in contract state and affects state dump. - // Therefore values are taken from C# node. + // NEF is now stored in the contract state and affects state dump. + // Therefore, values are taken from C# node. c.NEF.Header.Compiler = "neo-core-v3.0" c.NEF.Header.Magic = nef.Magic c.NEF.Tokens = []nef.MethodToken{} // avoid `nil` result during JSON marshalling @@ -175,7 +175,7 @@ func NewContractMD(name string, id int32) *ContractMD { return c } -// UpdateHash creates native contract script and updates hash. +// UpdateHash creates a native contract script and updates hash. func (c *ContractMD) UpdateHash() { w := io.NewBufBinWriter() for i := range c.Methods { @@ -195,7 +195,7 @@ func (c *ContractMD) UpdateHash() { c.NEF.Checksum = c.NEF.CalculateChecksum() } -// AddMethod adds new method to a native contract. +// AddMethod adds a new method to a native contract. func (c *ContractMD) AddMethod(md *MethodAndPrice, desc *manifest.Method) { md.MD = desc desc.Safe = md.RequiredFlags&(callflag.All^callflag.ReadOnly) == 0 @@ -217,7 +217,7 @@ func (c *ContractMD) AddMethod(md *MethodAndPrice, desc *manifest.Method) { c.Methods[index] = *md } -// GetMethodByOffset returns with the provided offset. +// GetMethodByOffset returns method with the provided offset. // Offset is offset of `System.Contract.CallNative` syscall. func (c *ContractMD) GetMethodByOffset(offset int) (MethodAndPrice, bool) { for k := range c.Methods { @@ -228,7 +228,7 @@ func (c *ContractMD) GetMethodByOffset(offset int) (MethodAndPrice, bool) { return MethodAndPrice{}, false } -// GetMethod returns method `name` with specified number of parameters. +// GetMethod returns method `name` with the specified number of parameters. func (c *ContractMD) GetMethod(name string, paramCount int) (MethodAndPrice, bool) { index := sort.Search(len(c.Methods), func(i int) bool { md := c.Methods[i] @@ -249,7 +249,7 @@ func (c *ContractMD) GetMethod(name string, paramCount int) (MethodAndPrice, boo return MethodAndPrice{}, false } -// AddEvent adds new event to a native contract. +// AddEvent adds a new event to the native contract. func (c *ContractMD) AddEvent(name string, ps ...manifest.Parameter) { c.Manifest.ABI.Events = append(c.Manifest.ABI.Events, manifest.Event{ Name: name, @@ -257,7 +257,7 @@ func (c *ContractMD) AddEvent(name string, ps ...manifest.Parameter) { }) } -// IsActive returns true iff the contract was deployed by the specified height. +// IsActive returns true if the contract was deployed by the specified height. func (c *ContractMD) IsActive(height uint32) bool { history := c.UpdateHistory return len(history) != 0 && history[0] <= height @@ -268,7 +268,7 @@ func Sort(fs []Function) { sort.Slice(fs, func(i, j int) bool { return fs[i].ID < fs[j].ID }) } -// GetContract returns contract by its hash in current interop context. +// GetContract returns a contract by its hash in the current interop context. func (ic *Context) GetContract(hash util.Uint160) (*state.Contract, error) { return ic.getContract(ic.DAO, hash) } @@ -310,7 +310,7 @@ func (ic *Context) SyscallHandler(_ *vm.VM, id uint32) error { return f.Func(ic) } -// SpawnVM spawns new VM with the specified gas limit and set context.VM field. +// SpawnVM spawns a new VM with the specified gas limit and set context.VM field. func (ic *Context) SpawnVM() *vm.VM { v := vm.NewWithTrigger(ic.Trigger) v.GasLimit = -1 @@ -319,7 +319,7 @@ func (ic *Context) SpawnVM() *vm.VM { return v } -// RegisterCancelFunc adds given function to the list of functions to be called after VM +// RegisterCancelFunc adds the given function to the list of functions to be called after the VM // finishes script execution. func (ic *Context) RegisterCancelFunc(f context.CancelFunc) { if f != nil { diff --git a/pkg/core/interop/contract/call.go b/pkg/core/interop/contract/call.go index 2afab663d..5627863ef 100644 --- a/pkg/core/interop/contract/call.go +++ b/pkg/core/interop/contract/call.go @@ -21,7 +21,7 @@ type policyChecker interface { IsBlocked(*dao.Simple, util.Uint160) bool } -// LoadToken calls method specified by token id. +// LoadToken calls method specified by the token id. func LoadToken(ic *interop.Context) func(id int32) error { return func(id int32) error { ctx := ic.VM.Context() @@ -91,7 +91,7 @@ func callInternal(ic *interop.Context, cs *state.Contract, name string, f callfl return callExFromNative(ic, ic.VM.GetCurrentScriptHash(), cs, name, args, f, hasReturn) } -// callExFromNative calls a contract with flags using provided calling hash. +// callExFromNative calls a contract with flags using the provided calling hash. func callExFromNative(ic *interop.Context, caller util.Uint160, cs *state.Contract, name string, args []stackitem.Item, f callflag.CallFlag, hasReturn bool) error { for _, nc := range ic.Natives { diff --git a/pkg/core/interop/runtime/util.go b/pkg/core/interop/runtime/util.go index 057d5c0da..e00345f87 100644 --- a/pkg/core/interop/runtime/util.go +++ b/pkg/core/interop/runtime/util.go @@ -15,7 +15,7 @@ import ( "github.com/twmb/murmur3" ) -// GasLeft returns remaining amount of GAS. +// GasLeft returns the remaining amount of GAS. func GasLeft(ic *interop.Context) error { if ic.VM.GasLimit == -1 { ic.VM.Estack().PushItem(stackitem.NewBigInteger(big.NewInt(ic.VM.GasLimit))) @@ -25,7 +25,7 @@ func GasLeft(ic *interop.Context) error { return nil } -// GetNotifications returns notifications emitted by current contract execution. +// GetNotifications returns notifications emitted in the current execution context. func GetNotifications(ic *interop.Context) error { item := ic.VM.Estack().Pop().Item() notifications := ic.Notifications @@ -61,7 +61,7 @@ func GetNotifications(ic *interop.Context) error { return nil } -// GetInvocationCounter returns how many times current contract was invoked during current tx execution. +// GetInvocationCounter returns how many times the current contract has been invoked during the current tx execution. func GetInvocationCounter(ic *interop.Context) error { currentScriptHash := ic.VM.GetCurrentScriptHash() count, ok := ic.Invocations[currentScriptHash] diff --git a/pkg/core/interop/runtime/witness.go b/pkg/core/interop/runtime/witness.go index ba5674993..d6a01e652 100644 --- a/pkg/core/interop/runtime/witness.go +++ b/pkg/core/interop/runtime/witness.go @@ -15,7 +15,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// CheckHashedWitness checks given hash against current list of script hashes +// CheckHashedWitness checks the given hash against the current list of script hashes // for verifying in the interop context. func CheckHashedWitness(ic *interop.Context, hash util.Uint160) (bool, error) { callingSH := ic.VM.GetCallingScriptHash() @@ -113,8 +113,8 @@ func checkScope(ic *interop.Context, hash util.Uint160) (bool, error) { return false, nil } -// CheckKeyedWitness checks hash of signature check contract with a given public -// key against current list of script hashes for verifying in the interop context. +// CheckKeyedWitness checks the hash of the signature check contract with the given public +// key against the current list of script hashes for verifying in the interop context. func CheckKeyedWitness(ic *interop.Context, key *keys.PublicKey) (bool, error) { return CheckHashedWitness(ic, key.GetScriptHash()) } diff --git a/pkg/core/interop/storage/find.go b/pkg/core/interop/storage/find.go index 35b6621f4..f86ca96f3 100644 --- a/pkg/core/interop/storage/find.go +++ b/pkg/core/interop/storage/find.go @@ -29,7 +29,7 @@ type Iterator struct { prefix []byte } -// NewIterator creates a new Iterator with given options for a given channel of store.Seek results. +// NewIterator creates a new Iterator with the given options for the given channel of store.Seek results. func NewIterator(seekCh chan storage.KeyValue, prefix []byte, opts int64) *Iterator { return &Iterator{ seekCh: seekCh, diff --git a/pkg/core/mempool/feer.go b/pkg/core/mempool/feer.go index 40b5d0743..55efd4eef 100644 --- a/pkg/core/mempool/feer.go +++ b/pkg/core/mempool/feer.go @@ -6,7 +6,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// Feer is an interface that abstract the implementation of the fee calculation. +// Feer is an interface that abstracts the implementation of the fee calculation. type Feer interface { FeePerByte() int64 GetUtilityTokenBalance(util.Uint160) *big.Int diff --git a/pkg/core/mempool/mem_pool.go b/pkg/core/mempool/mem_pool.go index e0790464e..d393f6e34 100644 --- a/pkg/core/mempool/mem_pool.go +++ b/pkg/core/mempool/mem_pool.go @@ -15,24 +15,24 @@ import ( ) var ( - // ErrInsufficientFunds is returned when Sender is not able to pay for - // transaction being added irrespective of the other contents of the + // ErrInsufficientFunds is returned when the Sender is not able to pay for + // the transaction being added irrespective of the other contents of the // pool. ErrInsufficientFunds = errors.New("insufficient funds") - // ErrConflict is returned when transaction being added is incompatible + // ErrConflict is returned when the transaction being added is incompatible // with the contents of the memory pool (Sender doesn't have enough GAS // to pay for all transactions in the pool). ErrConflict = errors.New("conflicts: insufficient funds for all pooled tx") - // ErrDup is returned when transaction being added is already present + // ErrDup is returned when the transaction being added is already present // in the memory pool. ErrDup = errors.New("already in the memory pool") - // ErrOOM is returned when transaction just doesn't fit in the memory + // ErrOOM is returned when the transaction just doesn't fit in the memory // pool because of its capacity constraints. ErrOOM = errors.New("out of memory") - // ErrConflictsAttribute is returned when transaction conflicts with other transactions + // ErrConflictsAttribute is returned when the transaction conflicts with other transactions // due to its (or theirs) Conflicts attributes. ErrConflictsAttribute = errors.New("conflicts with memory pool due to Conflicts attribute") - // ErrOracleResponse is returned when mempool already contains transaction + // ErrOracleResponse is returned when the mempool already contains a transaction // with the same oracle response ID and higher network fee. ErrOracleResponse = errors.New("conflicts with memory pool due to OracleResponse attribute") ) @@ -44,25 +44,25 @@ type item struct { data interface{} } -// items is a slice of item. +// items is a slice of an item. type items []item -// utilityBalanceAndFees stores sender's balance and overall fees of -// sender's transactions which are currently in mempool. +// utilityBalanceAndFees stores the sender's balance and overall fees of +// the sender's transactions which are currently in the mempool. type utilityBalanceAndFees struct { balance uint256.Int feeSum uint256.Int } -// Pool stores the unconfirms transactions. +// Pool stores the unconfirmed transactions. type Pool struct { lock sync.RWMutex verifiedMap map[util.Uint256]*transaction.Transaction verifiedTxes items fees map[util.Uint160]utilityBalanceAndFees - // conflicts is a map of hashes of transactions which are conflicting with the mempooled ones. + // conflicts is a map of the hashes of the transactions which are conflicting with the mempooled ones. conflicts map[util.Uint256][]util.Uint256 - // oracleResp contains ids of oracle responses for tx in pool. + // oracleResp contains the ids of oracle responses for the tx in the pool. oracleResp map[uint64]util.Uint256 capacity int @@ -106,7 +106,7 @@ func (p item) CompareTo(otherP item) int { return int(p.txn.NetworkFee - otherP.txn.NetworkFee) } -// Count returns the total number of uncofirm transactions. +// Count returns the total number of uncofirmed transactions. func (mp *Pool) Count() int { mp.lock.RLock() defer mp.lock.RUnlock() @@ -118,7 +118,7 @@ func (mp *Pool) count() int { return len(mp.verifiedTxes) } -// ContainsKey checks if a transactions hash is in the Pool. +// ContainsKey checks if the transactions hash is in the Pool. func (mp *Pool) ContainsKey(hash util.Uint256) bool { mp.lock.RLock() defer mp.lock.RUnlock() @@ -135,8 +135,8 @@ func (mp *Pool) containsKey(hash util.Uint256) bool { return false } -// HasConflicts returns true if transaction is already in pool or in the Conflicts attributes -// of pooled transactions or has Conflicts attributes for pooled transactions. +// HasConflicts returns true if the transaction is already in the pool or in the Conflicts attributes +// of the pooled transactions or has Conflicts attributes against the pooled transactions. func (mp *Pool) HasConflicts(t *transaction.Transaction, fee Feer) bool { mp.lock.RLock() defer mp.lock.RUnlock() @@ -158,8 +158,8 @@ func (mp *Pool) HasConflicts(t *transaction.Transaction, fee Feer) bool { return false } -// tryAddSendersFee tries to add system fee and network fee to the total sender`s fee in mempool -// and returns false if both balance check is required and sender has not enough GAS to pay. +// tryAddSendersFee tries to add system fee and network fee to the total sender`s fee in the mempool +// and returns false if both balance check is required and the sender does not have enough GAS to pay. func (mp *Pool) tryAddSendersFee(tx *transaction.Transaction, feer Feer, needCheck bool) bool { payer := tx.Signers[mp.payerIndex].Account senderFee, ok := mp.fees[payer] @@ -180,8 +180,8 @@ func (mp *Pool) tryAddSendersFee(tx *transaction.Transaction, feer Feer, needChe return true } -// checkBalance returns new cumulative fee balance for account or an error in -// case sender doesn't have enough GAS to pay for the transaction. +// checkBalance returns a new cumulative fee balance for the account or an error in +// case the sender doesn't have enough GAS to pay for the transaction. func checkBalance(tx *transaction.Transaction, balance utilityBalanceAndFees) (uint256.Int, error) { var txFee uint256.Int @@ -196,7 +196,7 @@ func checkBalance(tx *transaction.Transaction, balance utilityBalanceAndFees) (u return txFee, nil } -// Add tries to add given transaction to the Pool. +// Add tries to add the given transaction to the Pool. func (mp *Pool) Add(t *transaction.Transaction, fee Feer, data ...interface{}) error { var pItem = item{ txn: t, @@ -234,9 +234,9 @@ func (mp *Pool) Add(t *transaction.Transaction, fee Feer, data ...interface{}) e mp.removeInternal(conflictingTx.Hash(), fee) } } - // Insert into sorted array (from max to min, that could also be done + // Insert into a sorted array (from max to min, that could also be done // using sort.Sort(sort.Reverse()), but it incurs more overhead. Notice - // also that we're searching for position that is strictly more + // also that we're searching for a position that is strictly more // prioritized than our new item because we do expect a lot of // transactions with the same priority and appending to the end of the // slice is always more efficient. @@ -299,7 +299,7 @@ func (mp *Pool) Add(t *transaction.Transaction, fee Feer, data ...interface{}) e return nil } -// Remove removes an item from the mempool, if it exists there (and does +// Remove removes an item from the mempool if it exists there (and does // nothing if it doesn't). func (mp *Pool) Remove(hash util.Uint256, feer Feer) { mp.lock.Lock() @@ -346,8 +346,8 @@ func (mp *Pool) removeInternal(hash util.Uint256, feer Feer) { } // RemoveStale filters verified transactions through the given function keeping -// only the transactions for which it returns a true result. It's used to quickly -// drop part of the mempool that is now invalid after the block acceptance. +// only the transactions for which it returns true result. It's used to quickly +// drop a part of the mempool that is now invalid after the block acceptance. func (mp *Pool) RemoveStale(isOK func(*transaction.Transaction) bool, feer Feer) { mp.lock.Lock() policyChanged := mp.loadPolicy(feer) @@ -372,7 +372,7 @@ func (mp *Pool) RemoveStale(isOK func(*transaction.Transaction) bool, feer Feer) } } if mp.resendThreshold != 0 { - // item is resend at resendThreshold, 2*resendThreshold, 4*resendThreshold ... + // item is resent at resendThreshold, 2*resendThreshold, 4*resendThreshold ... // so quotient must be a power of two. diff := (height - itm.blockStamp) if diff%mp.resendThreshold == 0 && bits.OnesCount32(diff/mp.resendThreshold) == 1 { @@ -400,7 +400,7 @@ func (mp *Pool) RemoveStale(isOK func(*transaction.Transaction) bool, feer Feer) mp.lock.Unlock() } -// loadPolicy updates feePerByte field and returns whether policy has been +// loadPolicy updates feePerByte field and returns whether the policy has been // changed. func (mp *Pool) loadPolicy(feer Feer) bool { newFeePerByte := feer.FeePerByte() @@ -411,7 +411,7 @@ func (mp *Pool) loadPolicy(feer Feer) bool { return false } -// checkPolicy checks whether transaction fits policy. +// checkPolicy checks whether the transaction fits the policy. func (mp *Pool) checkPolicy(tx *transaction.Transaction, policyChanged bool) bool { if !policyChanged || tx.FeePerByte() >= mp.feePerByte { return true @@ -439,7 +439,7 @@ func New(capacity int, payerIndex int, enableSubscriptions bool) *Pool { return mp } -// SetResendThreshold sets threshold after which transaction will be considered stale +// SetResendThreshold sets a threshold after which the transaction will be considered stale // and returned for retransmission by `GetStaleTransactions`. func (mp *Pool) SetResendThreshold(h uint32, f func(*transaction.Transaction, interface{})) { mp.lock.Lock() @@ -555,10 +555,10 @@ func (mp *Pool) checkTxConflicts(tx *transaction.Transaction, fee Feer) ([]*tran return conflictsToBeRemoved, err } -// Verify checks if a Sender of tx is able to pay for it (and all the other +// Verify checks if the Sender of the tx is able to pay for it (and all the other // transactions in the pool). If yes, the transaction tx is a valid // transaction and the function returns true. If no, the transaction tx is -// considered to be invalid the function returns false. +// considered to be invalid, the function returns false. func (mp *Pool) Verify(tx *transaction.Transaction, feer Feer) bool { mp.lock.RLock() defer mp.lock.RUnlock() @@ -566,7 +566,7 @@ func (mp *Pool) Verify(tx *transaction.Transaction, feer Feer) bool { return err == nil } -// removeConflictsOf removes hash of the given transaction from the conflicts list +// removeConflictsOf removes the hash of the given transaction from the conflicts list // for each Conflicts attribute. func (mp *Pool) removeConflictsOf(tx *transaction.Transaction) { // remove all conflicting hashes from mp.conflicts list diff --git a/pkg/core/mempool/subscriptions.go b/pkg/core/mempool/subscriptions.go index 066d0651b..527ae370c 100644 --- a/pkg/core/mempool/subscriptions.go +++ b/pkg/core/mempool/subscriptions.go @@ -25,16 +25,16 @@ func (mp *Pool) StopSubscriptions() { } } -// SubscribeForTransactions adds given channel to new mempool event broadcasting, so when -// there is a new transactions added to mempool or an existing transaction removed from -// mempool you'll receive it via this channel. +// SubscribeForTransactions adds the given channel to the new mempool event broadcasting, so when +// there is a new transactions added to the mempool or an existing transaction removed from +// the mempool, you'll receive it via this channel. func (mp *Pool) SubscribeForTransactions(ch chan<- mempoolevent.Event) { if mp.subscriptionsOn.Load() { mp.subCh <- ch } } -// UnsubscribeFromTransactions unsubscribes given channel from new mempool notifications, +// UnsubscribeFromTransactions unsubscribes the given channel from new mempool notifications, // you can close it afterwards. Passing non-subscribed channel is a no-op. func (mp *Pool) UnsubscribeFromTransactions(ch chan<- mempoolevent.Event) { if mp.subscriptionsOn.Load() { diff --git a/pkg/core/mempoolevent/event.go b/pkg/core/mempoolevent/event.go index 5361c85a6..d59c07c8e 100644 --- a/pkg/core/mempoolevent/event.go +++ b/pkg/core/mempoolevent/event.go @@ -17,7 +17,7 @@ const ( TransactionRemoved Type = 0x02 ) -// Event represents one of mempool events: transaction was added or removed from mempool. +// Event represents one of mempool events: transaction was added or removed from the mempool. type Event struct { Type Type Tx *transaction.Transaction @@ -36,7 +36,7 @@ func (e Type) String() string { } } -// GetEventTypeFromString converts input string into an Type if it's possible. +// GetEventTypeFromString converts the input string into the Type if it's possible. func GetEventTypeFromString(s string) (Type, error) { switch s { case "added": @@ -48,12 +48,12 @@ func GetEventTypeFromString(s string) (Type, error) { } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (e Type) MarshalJSON() ([]byte, error) { return json.Marshal(e.String()) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (e *Type) UnmarshalJSON(b []byte) error { var s string diff --git a/pkg/core/mpt/base.go b/pkg/core/mpt/base.go index c2f7f2f11..a9aa207a0 100644 --- a/pkg/core/mpt/base.go +++ b/pkg/core/mpt/base.go @@ -36,7 +36,7 @@ func (b *BaseNode) setCache(bs []byte, h util.Uint256) { b.hashValid = true } -// getHash returns a hash of this BaseNode. +// getHash returns the hash of this BaseNode. func (b *BaseNode) getHash(n Node) util.Uint256 { if !b.hashValid { b.updateHash(n) @@ -52,7 +52,7 @@ func (b *BaseNode) getBytes(n Node) []byte { return b.bytes } -// updateHash updates hash field for this BaseNode. +// updateHash updates the hash field for this BaseNode. func (b *BaseNode) updateHash(n Node) { if n.Type() == HashT || n.Type() == EmptyT { panic("can't update hash for empty or hash node") @@ -61,7 +61,7 @@ func (b *BaseNode) updateHash(n Node) { b.hashValid = true } -// updateCache updates hash and bytes fields for this BaseNode. +// updateCache updates the hash and bytes fields for this BaseNode. func (b *BaseNode) updateBytes(n Node) { bw := io.NewBufBinWriter() bw.Grow(1 + n.Size()) @@ -85,13 +85,13 @@ func encodeBinaryAsChild(n Node, w *io.BinWriter) { w.WriteBytes(n.Hash().BytesBE()) } -// encodeNodeWithType encodes node together with it's type. +// encodeNodeWithType encodes the node together with its type. func encodeNodeWithType(n Node, w *io.BinWriter) { w.WriteB(byte(n.Type())) n.EncodeBinary(w) } -// DecodeNodeWithType decodes node together with it's type. +// DecodeNodeWithType decodes the node together with its type. func DecodeNodeWithType(r *io.BinReader) Node { if r.Err != nil { return nil diff --git a/pkg/core/mpt/batch.go b/pkg/core/mpt/batch.go index 3783edc95..420f2ebed 100644 --- a/pkg/core/mpt/batch.go +++ b/pkg/core/mpt/batch.go @@ -5,7 +5,7 @@ import ( "sort" ) -// Batch is batch of storage changes. +// Batch is a batch of storage changes. // It stores key-value pairs in a sorted state. type Batch struct { kv []keyValue @@ -16,7 +16,7 @@ type keyValue struct { value []byte } -// MapToMPTBatch makes a Batch from unordered set of storage changes. +// MapToMPTBatch makes a Batch from an unordered set of storage changes. func MapToMPTBatch(m map[string][]byte) Batch { var b Batch @@ -31,13 +31,13 @@ func MapToMPTBatch(m map[string][]byte) Batch { return b } -// PutBatch puts batch to trie. +// PutBatch puts a batch to a trie. // It is not atomic (and probably cannot be without substantial slow-down) -// and returns number of elements processed. +// and returns the number of elements processed. // If an error is returned, the trie may be in the inconsistent state in case of storage failures. // This is due to the fact that we can remove multiple children from the branch node simultaneously // and won't strip the resulting branch node. -// However it is used mostly after the block processing to update MPT and error is not expected. +// However, it is used mostly after block processing to update MPT, and error is not expected. func (t *Trie) PutBatch(b Batch) (int, error) { if len(b.kv) == 0 { return 0, nil @@ -150,13 +150,13 @@ func (t *Trie) addToBranch(b *BranchNode, kv []keyValue, inTrie bool) (Node, int t.removeRef(b.Hash(), b.bytes) } - // Error during iterate means some storage failure (i.e. some hash node cannot be - // retrieved from storage). This can leave trie in inconsistent state, because - // it can be impossible to strip branch node after it has been changed. + // An error during iterate means some storage failure (i.e. some hash node cannot be + // retrieved from storage). This can leave the trie in an inconsistent state because + // it can be impossible to strip the branch node after it has been changed. // Consider a branch with 10 children, first 9 of which are deleted and the remaining one - // is a leaf node replaced by a hash node missing from storage. - // This can't be fixed easily because we need to _revert_ changes in reference counts - // for children which were updated successfully. But storage access errors means we are + // is a leaf node replaced by a hash node missing from the storage. + // This can't be fixed easily because we need to _revert_ changes in the reference counts + // for children which have been updated successfully. But storage access errors means we are // in a bad state anyway. n, err := t.iterateBatch(kv, func(c byte, kv []keyValue) (int, error) { child, n, err := t.putBatchIntoNode(b.Children[c], kv) @@ -167,8 +167,8 @@ func (t *Trie) addToBranch(b *BranchNode, kv []keyValue, inTrie bool) (Node, int b.invalidateCache() } - // Even if some of the children can't be put, we need to try to strip branch - // and possibly update refcounts. + // Even if some of the children can't be put, we need to try to strip the branch + // and possibly update the refcounts. nd, bErr := t.stripBranch(b) if err == nil { err = bErr @@ -176,8 +176,8 @@ func (t *Trie) addToBranch(b *BranchNode, kv []keyValue, inTrie bool) (Node, int return nd, n, err } -// stripsBranch strips branch node after incomplete batch put. -// It assumes there is no reference to b in trie. +// stripsBranch strips the branch node after incomplete batch put. +// It assumes there is no reference to b in the trie. func (t *Trie) stripBranch(b *BranchNode) (Node, error) { var n int var lastIndex byte @@ -232,12 +232,12 @@ func (t *Trie) putBatchIntoHash(curr *HashNode, kv []keyValue) (Node, int, error return t.putBatchIntoNode(result, kv) } -// Creates new subtrie from provided key-value pairs. +// Creates a new subtrie from the provided key-value pairs. // Items in kv must have no common prefix. -// If there are any deletions in kv, return error. +// If there are any deletions in kv, error is returned. // kv is not empty. // kv is sorted by key. -// value is current value stored by prefix. +// value is the current value stored by prefix. func (t *Trie) newSubTrieMany(prefix []byte, kv []keyValue, value []byte) (Node, int, error) { if len(kv[0].key) == 0 { if kv[0].value == nil { diff --git a/pkg/core/mpt/billet.go b/pkg/core/mpt/billet.go index 40ee35de0..d145900f8 100644 --- a/pkg/core/mpt/billet.go +++ b/pkg/core/mpt/billet.go @@ -19,13 +19,13 @@ var ( errStop = errors.New("stop condition is met") ) -// Billet is a part of MPT trie with missing hash nodes that need to be restored. +// Billet is a part of an MPT trie with missing hash nodes that need to be restored. // Billet is based on the following assumptions: -// 1. Refcount can only be incremented (we don't change MPT structure during restore, +// 1. Refcount can only be incremented (we don't change the MPT structure during restore, // thus don't need to decrease refcount). -// 2. Each time the part of Billet is completely restored, it is collapsed into +// 2. Each time a part of a Billet is completely restored, it is collapsed into // HashNode. -// 3. Pair (node, path) must be restored only once. It's a duty of MPT pool to manage +// 3. Any pair (node, path) must be restored only once. It's a duty of an MPT pool to manage // MPT paths in order to provide this assumption. type Billet struct { TempStoragePrefix storage.KeyPrefix @@ -35,9 +35,9 @@ type Billet struct { mode TrieMode } -// NewBillet returns new billet for MPT trie restoring. It accepts a MemCachedStore +// NewBillet returns a new billet for MPT trie restoring. It accepts a MemCachedStore // to decouple storage errors from logic errors so that all storage errors are -// processed during `store.Persist()` at the caller. This also has the benefit, +// processed during `store.Persist()` at the caller. Another benifit is // that every `Put` can be considered an atomic operation. func NewBillet(rootHash util.Uint256, mode TrieMode, prefix storage.KeyPrefix, store *storage.MemCachedStore) *Billet { return &Billet{ @@ -49,8 +49,8 @@ func NewBillet(rootHash util.Uint256, mode TrieMode, prefix storage.KeyPrefix, s } // RestoreHashNode replaces HashNode located at the provided path by the specified Node -// and stores it. It also maintains MPT as small as possible by collapsing those parts -// of MPT that have been completely restored. +// and stores it. It also maintains the MPT as small as possible by collapsing those parts +// of the MPT that have been completely restored. func (b *Billet) RestoreHashNode(path []byte, node Node) error { if _, ok := node.(*HashNode); ok { return fmt.Errorf("%w: unable to restore node into HashNode", ErrRestoreFailed) @@ -75,7 +75,7 @@ func (b *Billet) RestoreHashNode(path []byte, node Node) error { return nil } -// putIntoNode puts val with provided path inside curr and returns updated node. +// putIntoNode puts val with the provided path inside curr and returns an updated node. // Reference counters are updated for both curr and returned value. func (b *Billet) putIntoNode(curr Node, path []byte, val Node) (Node, error) { switch n := curr.(type) { @@ -102,7 +102,7 @@ func (b *Billet) putIntoLeaf(curr *LeafNode, path []byte, val Node) (Node, error return nil, fmt.Errorf("%w: bad Leaf node hash: expected %s, got %s", ErrRestoreFailed, curr.Hash().StringBE(), val.Hash().StringBE()) } // Once Leaf node is restored, it will be collapsed into HashNode forever, so - // there shouldn't be such situation when we try to restore Leaf node. + // there shouldn't be such situation when we try to restore a Leaf node. panic("bug: can't restore LeafNode") } @@ -143,15 +143,15 @@ func (b *Billet) putIntoExtension(curr *ExtensionNode, path []byte, val Node) (N } func (b *Billet) putIntoHash(curr *HashNode, path []byte, val Node) (Node, error) { - // Once a part of MPT Billet is completely restored, it will be collapsed forever, so + // Once a part of the MPT Billet is completely restored, it will be collapsed forever, so // it's an MPT pool duty to avoid duplicating restore requests. if len(path) != 0 { return nil, fmt.Errorf("%w: node has already been collapsed", ErrRestoreFailed) } // `curr` hash node can be either of - // 1) saved in storage (i.g. if we've already restored node with the same hash from the - // other part of MPT), so just add it to local in-memory MPT. + // 1) saved in the storage (i.g. if we've already restored a node with the same hash from the + // other part of the MPT), so just add it to the local in-memory MPT. // 2) missing from the storage. It's OK because we're syncing MPT state, and the purpose // is to store missing hash nodes. // both cases are OK, but we still need to validate `val` against `curr`. diff --git a/pkg/core/mpt/branch.go b/pkg/core/mpt/branch.go index d2fc84dfc..3f7317b23 100644 --- a/pkg/core/mpt/branch.go +++ b/pkg/core/mpt/branch.go @@ -9,13 +9,13 @@ import ( ) const ( - // childrenCount represents a number of children of a branch node. + // childrenCount represents the number of children of a branch node. childrenCount = 17 // lastChild is the index of the last child. lastChild = childrenCount - 1 ) -// BranchNode represents MPT's branch node. +// BranchNode represents an MPT's branch node. type BranchNode struct { BaseNode Children [childrenCount]Node @@ -23,7 +23,7 @@ type BranchNode struct { var _ Node = (*BranchNode)(nil) -// NewBranchNode returns new branch node. +// NewBranchNode returns a new branch node. func NewBranchNode() *BranchNode { b := new(BranchNode) for i := 0; i < childrenCount; i++ { @@ -32,20 +32,20 @@ func NewBranchNode() *BranchNode { return b } -// Type implements Node interface. +// Type implements the Node interface. func (b *BranchNode) Type() NodeType { return BranchT } -// Hash implements BaseNode interface. +// Hash implements the BaseNode interface. func (b *BranchNode) Hash() util.Uint256 { return b.getHash(b) } -// Bytes implements BaseNode interface. +// Bytes implements the BaseNode interface. func (b *BranchNode) Bytes() []byte { return b.getBytes(b) } -// Size implements Node interface. +// Size implements the Node interface. func (b *BranchNode) Size() int { sz := childrenCount for i := range b.Children { @@ -72,12 +72,12 @@ func (b *BranchNode) DecodeBinary(r *io.BinReader) { } } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (b *BranchNode) MarshalJSON() ([]byte, error) { return json.Marshal(b.Children) } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (b *BranchNode) UnmarshalJSON(data []byte) error { var obj NodeObject if err := obj.UnmarshalJSON(data); err != nil { diff --git a/pkg/core/mpt/compat_test.go b/pkg/core/mpt/compat_test.go index 7ac16c83a..147568829 100644 --- a/pkg/core/mpt/compat_test.go +++ b/pkg/core/mpt/compat_test.go @@ -37,15 +37,15 @@ func prepareMPTCompat() *Trie { // TestCompatibility contains tests present in C# implementation. // https://github.com/neo-project/neo-modules/blob/master/tests/Neo.Plugins.StateService.Tests/MPT/UT_MPTTrie.cs // There are some differences, though: -// 1. In our implementation delete is silent, i.e. we do not return an error is the key is missing or empty. -// However, we do return error when contents of hash node are missing from the store +// 1. In our implementation, delete is silent, i.e. we do not return an error if the key is missing or empty. +// However, we do return an error when the contents of the hash node are missing from the store // (corresponds to exception in C# implementation). However, if the key is too big, an error is returned // (corresponds to exception in C# implementation). -// 2. In our implementation put returns error if something goes wrong, while C# implementation throws +// 2. In our implementation, put returns an error if something goes wrong, while C# implementation throws // an exception and returns nothing. -// 3. In our implementation get does not immediately return error in case of an empty key. An error is returned -// only if value is missing from the storage. C# implementation checks that key is not empty and throws an error -// otherwice. However, if the key is too big, an error is returned (corresponds to exception in C# implementation). +// 3. In our implementation, get does not immediately return any error in case of an empty key. An error is returned +// only if the value is missing from the storage. C# implementation checks that the key is not empty and throws an error +// otherwise. However, if the key is too big, an error is returned (corresponds to exception in C# implementation). func TestCompatibility(t *testing.T) { mainTrie := prepareMPTCompat() diff --git a/pkg/core/mpt/doc.go b/pkg/core/mpt/doc.go index c307665b3..41dacdd0b 100644 --- a/pkg/core/mpt/doc.go +++ b/pkg/core/mpt/doc.go @@ -1,14 +1,14 @@ /* -Package mpt implements MPT (Merkle-Patricia Tree). +Package mpt implements MPT (Merkle-Patricia Trie). -MPT stores key-value pairs and is a trie over 16-symbol alphabet. https://en.wikipedia.org/wiki/Trie -Trie is a tree where values are stored in leafs and keys are paths from root to the leaf node. -MPT consists of 4 type of nodes: -- Leaf node contains only value. -- Extension node contains both key and value. +An MPT stores key-value pairs and is a trie over 16-symbol alphabet. https://en.wikipedia.org/wiki/Trie +A trie is a tree where values are stored in leafs and keys are paths from the root to the leaf node. +An MPT consists of 4 types of nodes: +- Leaf node only contains a value. +- Extension node contains both a key and a value. - Branch node contains 2 or more children. -- Hash node is a compressed node and contains only actual node's hash. - The actual node must be retrieved from storage or over the network. +- Hash node is a compressed node and only contains the actual node's hash. + The actual node must be retrieved from the storage or over the network. As an example here is a trie containing 3 pairs: - 0x1201 -> val1 @@ -31,15 +31,15 @@ BranchNode [0, 1, 2, ...], Last -> Leaf(val4) There are 3 invariants that this implementation has: - Branch node cannot have <= 1 children -- Extension node cannot have zero-length key -- Extension node cannot have another Extension node in it's next field +- Extension node cannot have a zero-length key +- Extension node cannot have another Extension node in its next field -Thank to these restrictions, there is a single root hash for every set of key-value pairs -irregardless of the order they were added/removed with. +Thanks to these restrictions, there is a single root hash for every set of key-value pairs +irregardless of the order they were added/removed in. The actual trie structure can vary because of node -> HashNode compressing. -There is also one optimization which cost us almost nothing in terms of complexity but is very beneficial: -When we perform get/put/delete on a speficic path, every Hash node which was retreived from storage is -replaced by its uncompressed form, so that subsequent hits of this not don't use storage. +There is also one optimization which cost us almost nothing in terms of complexity but is quite beneficial: +When we perform get/put/delete on a specific path, every Hash node which was retrieved from the storage is +replaced by its uncompressed form, so that subsequent hits of this don't need to access the storage. */ package mpt diff --git a/pkg/core/mpt/empty.go b/pkg/core/mpt/empty.go index bc4f4914a..b3ceec873 100644 --- a/pkg/core/mpt/empty.go +++ b/pkg/core/mpt/empty.go @@ -8,14 +8,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// EmptyNode represents empty node. +// EmptyNode represents an empty node. type EmptyNode struct{} -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (e EmptyNode) DecodeBinary(*io.BinReader) { } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (e EmptyNode) EncodeBinary(*io.BinWriter) { } diff --git a/pkg/core/mpt/extension.go b/pkg/core/mpt/extension.go index 1266c6acb..518cc2787 100644 --- a/pkg/core/mpt/extension.go +++ b/pkg/core/mpt/extension.go @@ -15,12 +15,12 @@ const ( // maxPathLength is the max length of the extension node key. maxPathLength = (storage.MaxStorageKeyLen + 4) * 2 - // MaxKeyLength is the max length of the key to put in trie + // MaxKeyLength is the max length of the key to put in the trie // before transforming to nibbles. MaxKeyLength = maxPathLength / 2 ) -// ExtensionNode represents MPT's extension node. +// ExtensionNode represents an MPT's extension node. type ExtensionNode struct { BaseNode key []byte @@ -29,8 +29,8 @@ type ExtensionNode struct { var _ Node = (*ExtensionNode)(nil) -// NewExtensionNode returns hash node with the specified key and next node. -// Note: because it is a part of Trie, key must be mangled, i.e. must contain only bytes with high half = 0. +// NewExtensionNode returns a hash node with the specified key and the next node. +// Note: since it is a part of a Trie, the key must be mangled, i.e. must contain only bytes with high half = 0. func NewExtensionNode(key []byte, next Node) *ExtensionNode { return &ExtensionNode{ key: key, @@ -78,7 +78,7 @@ func (e *ExtensionNode) Size() int { 1 + util.Uint256Size // e.next is never empty } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (e *ExtensionNode) MarshalJSON() ([]byte, error) { m := map[string]interface{}{ "key": hex.EncodeToString(e.key), @@ -87,7 +87,7 @@ func (e *ExtensionNode) MarshalJSON() ([]byte, error) { return json.Marshal(m) } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (e *ExtensionNode) UnmarshalJSON(data []byte) error { var obj NodeObject if err := obj.UnmarshalJSON(data); err != nil { diff --git a/pkg/core/mpt/hash.go b/pkg/core/mpt/hash.go index 03dc47a36..3bc66481f 100644 --- a/pkg/core/mpt/hash.go +++ b/pkg/core/mpt/hash.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// HashNode represents MPT's hash node. +// HashNode represents an MPT's hash node. type HashNode struct { BaseNode Collapsed bool @@ -15,7 +15,7 @@ type HashNode struct { var _ Node = (*HashNode)(nil) -// NewHashNode returns hash node with the specified hash. +// NewHashNode returns a hash node with the specified hash. func NewHashNode(h util.Uint256) *HashNode { return &HashNode{ BaseNode: BaseNode{ @@ -61,12 +61,12 @@ func (h HashNode) EncodeBinary(w *io.BinWriter) { w.WriteBytes(h.hash[:]) } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (h *HashNode) MarshalJSON() ([]byte, error) { return []byte(`{"hash":"` + h.hash.StringLE() + `"}`), nil } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (h *HashNode) UnmarshalJSON(data []byte) error { var obj NodeObject if err := obj.UnmarshalJSON(data); err != nil { diff --git a/pkg/core/mpt/helpers.go b/pkg/core/mpt/helpers.go index 0490cb122..27167c593 100644 --- a/pkg/core/mpt/helpers.go +++ b/pkg/core/mpt/helpers.go @@ -2,7 +2,7 @@ package mpt import "github.com/nspcc-dev/neo-go/pkg/util" -// lcp returns longest common prefix of a and b. +// lcp returns the longest common prefix of a and b. // Note: it does no allocations. func lcp(a, b []byte) []byte { if len(a) < len(b) { @@ -33,7 +33,7 @@ func lcpMany(kv []keyValue) []byte { return p } -// toNibbles mangles path by splitting every byte into 2 containing low- and high- 4-byte part. +// toNibbles mangles the path by splitting every byte into 2 containing low- and high- 4-byte part. func toNibbles(path []byte) []byte { result := make([]byte, len(path)*2) for i := range path { @@ -43,7 +43,7 @@ func toNibbles(path []byte) []byte { return result } -// strToNibbles mangles path by splitting every byte into 2 containing low- and high- 4-byte part, +// strToNibbles mangles the path by splitting every byte into 2 containing low- and high- 4-byte part, // ignoring the first byte (prefix). func strToNibbles(path string) []byte { result := make([]byte, (len(path)-1)*2) @@ -54,7 +54,7 @@ func strToNibbles(path string) []byte { return result } -// fromNibbles performs operation opposite to toNibbles and does no path validity checks. +// fromNibbles performs an operation opposite to toNibbles and runs no path validity checks. func fromNibbles(path []byte) []byte { result := make([]byte, len(path)/2) for i := range result { @@ -63,7 +63,7 @@ func fromNibbles(path []byte) []byte { return result } -// GetChildrenPaths returns a set of paths to node's children who are non-empty HashNodes +// GetChildrenPaths returns a set of paths to the node's children who are non-empty HashNodes // based on the node's path. func GetChildrenPaths(path []byte, node Node) map[util.Uint256][][]byte { res := make(map[util.Uint256][][]byte) diff --git a/pkg/core/mpt/leaf.go b/pkg/core/mpt/leaf.go index 0efa45e70..ce3f36f22 100644 --- a/pkg/core/mpt/leaf.go +++ b/pkg/core/mpt/leaf.go @@ -10,10 +10,10 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// MaxValueLength is a max length of a leaf node value. +// MaxValueLength is the max length of a leaf node value. const MaxValueLength = 3 + storage.MaxStorageValueLen + 1 -// LeafNode represents MPT's leaf node. +// LeafNode represents an MPT's leaf node. type LeafNode struct { BaseNode value []byte @@ -21,7 +21,7 @@ type LeafNode struct { var _ Node = (*LeafNode)(nil) -// NewLeafNode returns hash node with the specified value. +// NewLeafNode returns a hash node with the specified value. func NewLeafNode(value []byte) *LeafNode { return &LeafNode{value: value} } @@ -61,12 +61,12 @@ func (n *LeafNode) Size() int { return io.GetVarSize(len(n.value)) + len(n.value) } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (n *LeafNode) MarshalJSON() ([]byte, error) { return []byte(`{"value":"` + hex.EncodeToString(n.value) + `"}`), nil } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (n *LeafNode) UnmarshalJSON(data []byte) error { var obj NodeObject if err := obj.UnmarshalJSON(data); err != nil { diff --git a/pkg/core/mpt/node.go b/pkg/core/mpt/node.go index a5f6cc814..a925b3d59 100644 --- a/pkg/core/mpt/node.go +++ b/pkg/core/mpt/node.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// NodeType represents node type.. +// NodeType represents a node type.. type NodeType byte // Node types definitions. @@ -21,14 +21,14 @@ const ( EmptyT NodeType = 0x04 ) -// NodeObject represents Node together with it's type. +// NodeObject represents a Node together with it's type. // It is used for serialization/deserialization where type info // is also expected. type NodeObject struct { Node } -// Node represents common interface of all MPT nodes. +// Node represents a common interface of all MPT nodes. type Node interface { io.Serializable json.Marshaler @@ -48,7 +48,7 @@ func (n *NodeObject) DecodeBinary(r *io.BinReader) { n.Node = DecodeNodeWithType(r) } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (n *NodeObject) UnmarshalJSON(data []byte) error { var m map[string]json.RawMessage err := json.Unmarshal(data, &m) diff --git a/pkg/core/mpt/proof.go b/pkg/core/mpt/proof.go index 74b25e7d4..7a02ebbb9 100644 --- a/pkg/core/mpt/proof.go +++ b/pkg/core/mpt/proof.go @@ -10,8 +10,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util/slice" ) -// GetProof returns a proof that key belongs to t. -// Proof consist of serialized nodes occurring on path from the root to the leaf of key. +// GetProof returns a proof that the key belongs to t. +// The proof consists of serialized nodes occurring on the path from the root to the leaf of key. func (t *Trie) GetProof(key []byte) ([][]byte, error) { var proof [][]byte if len(key) > MaxKeyLength { @@ -63,7 +63,7 @@ func (t *Trie) getProof(curr Node, path []byte, proofs *[][]byte) (Node, error) } // VerifyProof verifies that path indeed belongs to a MPT with the specified root hash. -// It also returns value for the key. +// It also returns the value for the key. func VerifyProof(rh util.Uint256, key []byte, proofs [][]byte) ([]byte, bool) { path := toNibbles(key) tr := NewTrie(NewHashNode(rh), ModeAll, storage.NewMemCachedStore(storage.NewMemoryStore())) diff --git a/pkg/core/mpt/trie.go b/pkg/core/mpt/trie.go index 90352af3d..046b074fb 100644 --- a/pkg/core/mpt/trie.go +++ b/pkg/core/mpt/trie.go @@ -12,10 +12,10 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util/slice" ) -// TrieMode is the storage mode of trie, it affects the DB scheme. +// TrieMode is the storage mode of a trie, it affects the DB scheme. type TrieMode byte -// TrieMode is the storage mode of trie. +// TrieMode is the storage mode of a trie. const ( // ModeAll is used to store everything. ModeAll TrieMode = 0 @@ -43,7 +43,7 @@ type cachedNode struct { refcount int32 } -// ErrNotFound is returned when requested trie item is missing. +// ErrNotFound is returned when the requested trie item is missing. var ErrNotFound = errors.New("item not found") // RC returns true when reference counting is enabled. @@ -56,9 +56,9 @@ func (m TrieMode) GC() bool { return m&ModeGCFlag != 0 } -// NewTrie returns new MPT trie. It accepts a MemCachedStore to decouple storage errors from logic errors +// NewTrie returns a new MPT trie. It accepts a MemCachedStore to decouple storage errors from logic errors, // so that all storage errors are processed during `store.Persist()` at the caller. -// This also has the benefit, that every `Put` can be considered an atomic operation. +// Another benefit is that every `Put` can be considered an atomic operation. func NewTrie(root Node, mode TrieMode, store *storage.MemCachedStore) *Trie { if root == nil { root = EmptyNode{} @@ -73,7 +73,7 @@ func NewTrie(root Node, mode TrieMode, store *storage.MemCachedStore) *Trie { } } -// Get returns value for the provided key in t. +// Get returns the value for the provided key in t. func (t *Trie) Get(key []byte) ([]byte, error) { if len(key) > MaxKeyLength { return nil, errors.New("key is too big") @@ -87,11 +87,11 @@ func (t *Trie) Get(key []byte) ([]byte, error) { return slice.Copy(leaf.(*LeafNode).value), nil } -// getWithPath returns a current node with all hash nodes along the path replaced -// to their "unhashed" counterparts. It also returns node the provided path in a -// subtrie rooting in curr points to. In case of `strict` set to `false` the -// provided path can be incomplete, so it also returns full path that points to -// the node found at the specified incomplete path. In case of `strict` set to `true` +// getWithPath returns the current node with all hash nodes along the path replaced +// with their "unhashed" counterparts. It also returns node which the provided path in a +// subtrie rooting in curr points to. In case of `strict` set to `false`, the +// provided path can be incomplete, so it also returns the full path that points to +// the node found at the specified incomplete path. In case of `strict` set to `true`, // the resulting path matches the provided one. func (t *Trie) getWithPath(curr Node, path []byte, strict bool) (Node, Node, []byte, error) { switch n := curr.(type) { @@ -159,8 +159,8 @@ func (t *Trie) Put(key, value []byte) error { return nil } -// putIntoLeaf puts val to trie if current node is a Leaf. -// It returns Node if curr needs to be replaced and error if any. +// putIntoLeaf puts the val to the trie if the current node is a Leaf. +// It returns a Node if curr needs to be replaced and an error has occurred, if any. func (t *Trie) putIntoLeaf(curr *LeafNode, path []byte, val Node) (Node, error) { v := val.(*LeafNode) if len(path) == 0 { @@ -176,8 +176,8 @@ func (t *Trie) putIntoLeaf(curr *LeafNode, path []byte, val Node) (Node, error) return b, nil } -// putIntoBranch puts val to trie if current node is a Branch. -// It returns Node if curr needs to be replaced and error if any. +// putIntoBranch puts the val to the trie if the current node is a Branch. +// It returns the Node if curr needs to be replaced and an error has occurred, if any. func (t *Trie) putIntoBranch(curr *BranchNode, path []byte, val Node) (Node, error) { i, path := splitPath(path) t.removeRef(curr.Hash(), curr.bytes) @@ -191,8 +191,8 @@ func (t *Trie) putIntoBranch(curr *BranchNode, path []byte, val Node) (Node, err return curr, nil } -// putIntoExtension puts val to trie if current node is an Extension. -// It returns Node if curr needs to be replaced and error if any. +// putIntoExtension puts the val to the trie if the current node is an Extension. +// It returns the Node if curr needs to be replaced and an error has occurred, if any. func (t *Trie) putIntoExtension(curr *ExtensionNode, path []byte, val Node) (Node, error) { t.removeRef(curr.Hash(), curr.bytes) if bytes.HasPrefix(path, curr.key) { @@ -232,8 +232,8 @@ func (t *Trie) putIntoEmpty(path []byte, val Node) (Node, error) { return t.newSubTrie(path, val, true), nil } -// putIntoHash puts val to trie if current node is a HashNode. -// It returns Node if curr needs to be replaced and error if any. +// putIntoHash puts the val to the trie if the current node is a HashNode. +// It returns the Node if curr needs to be replaced and an error has occurred, if any. func (t *Trie) putIntoHash(curr *HashNode, path []byte, val Node) (Node, error) { result, err := t.getFromStore(curr.hash) if err != nil { @@ -242,7 +242,7 @@ func (t *Trie) putIntoHash(curr *HashNode, path []byte, val Node) (Node, error) return t.putIntoNode(result, path, val) } -// newSubTrie create new trie containing node at provided path. +// newSubTrie creates a new trie containing the node at the provided path. func (t *Trie) newSubTrie(path []byte, val Node, newVal bool) Node { if newVal { t.addRef(val.Hash(), val.Bytes()) @@ -255,7 +255,7 @@ func (t *Trie) newSubTrie(path []byte, val Node, newVal bool) Node { return e } -// putIntoNode puts val with provided path inside curr and returns updated node. +// putIntoNode puts the val with the provided path inside curr and returns an updated node. // Reference counters are updated for both curr and returned value. func (t *Trie) putIntoNode(curr Node, path []byte, val Node) (Node, error) { switch n := curr.(type) { @@ -274,8 +274,8 @@ func (t *Trie) putIntoNode(curr Node, path []byte, val Node) (Node, error) { } } -// Delete removes key from trie. -// It returns no error on missing key. +// Delete removes the key from the trie. +// It returns no error on a missing key. func (t *Trie) Delete(key []byte) error { if len(key) > MaxKeyLength { return errors.New("key is too big") @@ -363,7 +363,7 @@ func (t *Trie) deleteFromExtension(n *ExtensionNode, path []byte) (Node, error) return n, nil } -// deleteFromNode removes value with provided path from curr and returns an updated node. +// deleteFromNode removes the value with the provided path from curr and returns an updated node. // Reference counters are updated for both curr and returned value. func (t *Trie) deleteFromNode(curr Node, path []byte) (Node, error) { switch n := curr.(type) { @@ -402,9 +402,9 @@ func makeStorageKey(mptKey util.Uint256) []byte { return append([]byte{byte(storage.DataMPT)}, mptKey[:]...) } -// Flush puts every node in the trie except Hash ones to the storage. -// Because we care only about block-level changes, there is no need to put every -// new node to storage. Normally, flush should be called with every StateRoot persist, i.e. +// Flush puts every node (except Hash ones) in the trie to the storage. +// Because we care about block-level changes only, there is no need to put every +// new node to the storage. Normally, flush should be called with every StateRoot persist, i.e. // after every block. func (t *Trie) Flush(index uint32) { key := makeStorageKey(util.Uint256{}) @@ -571,7 +571,7 @@ func collapse(depth int, node Node) Node { return node } -// Find returns list of storage key-value pairs whose key is prefixed by the specified +// Find returns a list of storage key-value pairs whose key is prefixed by the specified // prefix starting from the specified `prefix`+`from` path (not including the item at // the specified `prefix`+`from` path if so). The `max` number of elements is returned at max. func (t *Trie) Find(prefix, from []byte, max int) ([]storage.KeyValue, error) { diff --git a/pkg/core/native/contract.go b/pkg/core/native/contract.go index d6deaa375..318e28abe 100644 --- a/pkg/core/native/contract.go +++ b/pkg/core/native/contract.go @@ -27,13 +27,13 @@ type Contracts struct { Crypto *Crypto Std *Std Contracts []interop.Contract - // persistScript is vm script which executes "onPersist" method of every native contract. + // persistScript is a vm script which executes "onPersist" method of every native contract. persistScript []byte - // postPersistScript is vm script which executes "postPersist" method of every native contract. + // postPersistScript is a vm script which executes "postPersist" method of every native contract. postPersistScript []byte } -// ByHash returns native contract with the specified hash. +// ByHash returns a native contract with the specified hash. func (cs *Contracts) ByHash(h util.Uint160) interop.Contract { for _, ctr := range cs.Contracts { if ctr.Metadata().Hash.Equals(h) { @@ -43,7 +43,7 @@ func (cs *Contracts) ByHash(h util.Uint160) interop.Contract { return nil } -// ByName returns native contract with the specified name. +// ByName returns a native contract with the specified name. func (cs *Contracts) ByName(name string) interop.Contract { name = strings.ToLower(name) for _, ctr := range cs.Contracts { @@ -54,7 +54,7 @@ func (cs *Contracts) ByName(name string) interop.Contract { return nil } -// NewContracts returns new set of native contracts with new GAS, NEO, Policy, Oracle, +// NewContracts returns a new set of native contracts with new GAS, NEO, Policy, Oracle, // Designate and (optional) Notary contracts. func NewContracts(cfg config.ProtocolConfiguration) *Contracts { cs := new(Contracts) @@ -122,7 +122,7 @@ func NewContracts(cfg config.ProtocolConfiguration) *Contracts { return cs } -// GetPersistScript returns VM script calling "onPersist" syscall for native contracts. +// GetPersistScript returns a VM script calling "onPersist" syscall for native contracts. func (cs *Contracts) GetPersistScript() []byte { if cs.persistScript != nil { return cs.persistScript @@ -133,7 +133,7 @@ func (cs *Contracts) GetPersistScript() []byte { return cs.persistScript } -// GetPostPersistScript returns VM script calling "postPersist" syscall for native contracts. +// GetPostPersistScript returns a VM script calling "postPersist" syscall for native contracts. func (cs *Contracts) GetPostPersistScript() []byte { if cs.postPersistScript != nil { return cs.postPersistScript diff --git a/pkg/core/native/crypto.go b/pkg/core/native/crypto.go index 0eb4d6add..8738a3a21 100644 --- a/pkg/core/native/crypto.go +++ b/pkg/core/native/crypto.go @@ -137,22 +137,22 @@ func curveFromStackitem(si stackitem.Item) (elliptic.Curve, error) { } } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (c *Crypto) Metadata() *interop.ContractMD { return &c.ContractMD } -// Initialize implements Contract interface. +// Initialize implements the Contract interface. func (c *Crypto) Initialize(ic *interop.Context) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (c *Crypto) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (c *Crypto) PostPersist(ic *interop.Context) error { return nil } diff --git a/pkg/core/native/designate.go b/pkg/core/native/designate.go index e57e3c598..d4d92cdf6 100644 --- a/pkg/core/native/designate.go +++ b/pkg/core/native/designate.go @@ -27,7 +27,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Designate represents designation contract. +// Designate represents a designation contract. type Designate struct { interop.ContractMD NEO *NEO @@ -36,9 +36,9 @@ type Designate struct { p2pSigExtensionsEnabled bool OracleService atomic.Value - // NotaryService represents Notary node module. + // NotaryService represents a Notary node module. NotaryService atomic.Value - // StateRootService represents StateRoot node module. + // StateRootService represents a StateRoot node module. StateRootService *stateroot.Module } @@ -64,7 +64,7 @@ const ( // maxNodeCount is the maximum number of nodes to set the role for. maxNodeCount = 32 - // DesignationEventName is the name of a designation event. + // DesignationEventName is the name of the designation event. DesignationEventName = "Designation" ) @@ -150,12 +150,12 @@ func (s *Designate) InitializeCache(d *dao.Simple) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (s *Designate) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (s *Designate) PostPersist(ic *interop.Context) error { cache := ic.DAO.GetRWCache(s.ID).(*DesignationCache) if !cache.rolesChangedFlag { @@ -268,7 +268,7 @@ func getCachedRoleData(cache *DesignationCache, r noderoles.Role) *roleData { return nil } -// GetLastDesignatedHash returns last designated hash of a given role. +// GetLastDesignatedHash returns the last designated hash of the given role. func (s *Designate) GetLastDesignatedHash(d *dao.Simple, r noderoles.Role) (util.Uint160, error) { if !s.isValidRole(r) { return util.Uint160{}, ErrInvalidRole diff --git a/pkg/core/native/interop.go b/pkg/core/native/interop.go index 28fd6edc4..a7d97dce4 100644 --- a/pkg/core/native/interop.go +++ b/pkg/core/native/interop.go @@ -10,7 +10,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Call calls specified native contract method. +// Call calls the specified native contract method. func Call(ic *interop.Context) error { version := ic.VM.Estack().Pop().BigInt().Int64() if version != 0 { diff --git a/pkg/core/native/ledger.go b/pkg/core/native/ledger.go index dabd443a8..5752ec6f8 100644 --- a/pkg/core/native/ledger.go +++ b/pkg/core/native/ledger.go @@ -28,7 +28,7 @@ type Ledger struct { const ledgerContractID = -4 -// newLedger creates new Ledger native contract. +// newLedger creates a new Ledger native contract. func newLedger() *Ledger { var l = &Ledger{ ContractMD: *interop.NewContractMD(nativenames.Ledger, ledgerContractID), @@ -77,17 +77,17 @@ func newLedger() *Ledger { return l } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (l *Ledger) Metadata() *interop.ContractMD { return &l.ContractMD } -// Initialize implements Contract interface. +// Initialize implements the Contract interface. func (l *Ledger) Initialize(ic *interop.Context) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (l *Ledger) OnPersist(ic *interop.Context) error { // Actual block/tx processing is done in Blockchain.storeBlock(). // Even though C# node add them to storage here, they're not @@ -96,7 +96,7 @@ func (l *Ledger) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (l *Ledger) PostPersist(ic *interop.Context) error { return nil // Actual block/tx processing is done in Blockchain.storeBlock(). } @@ -139,8 +139,8 @@ func (l *Ledger) getTransactionHeight(ic *interop.Context, params []stackitem.It return stackitem.Make(h) } -// getTransactionFromBlock returns transaction with the given index from the -// block with height or hash specified. +// getTransactionFromBlock returns a transaction with the given index from the +// block with the height or hash specified. func (l *Ledger) getTransactionFromBlock(ic *interop.Context, params []stackitem.Item) stackitem.Item { hash := getBlockHashFromItem(ic, params[0]) index := toUint32(params[1]) @@ -177,14 +177,14 @@ func (l *Ledger) getTransactionVMState(ic *interop.Context, params []stackitem.I } // isTraceableBlock defines whether we're able to give information about -// the block with index specified. +// the block with the index specified. func isTraceableBlock(ic *interop.Context, index uint32) bool { height := ic.BlockHeight() MaxTraceableBlocks := ic.Chain.GetConfig().MaxTraceableBlocks return index <= height && index+MaxTraceableBlocks > height } -// getBlockHashFromItem converts given stackitem.Item to block hash using given +// getBlockHashFromItem converts the given stackitem.Item to a block hash using the given // Ledger if needed. Interop functions accept both block numbers and // block hashes as parameters, thus this function is needed. It's supposed to // be called within VM context, so it panics if anything goes wrong. @@ -219,7 +219,7 @@ func getUint256FromItem(item stackitem.Item) (util.Uint256, error) { return hash, nil } -// getTransactionAndHeight returns transaction and its height if it's present +// getTransactionAndHeight returns a transaction and its height if it's present // on the chain. It panics if anything goes wrong. func getTransactionAndHeight(d *dao.Simple, item stackitem.Item) (*transaction.Transaction, uint32, error) { hash, err := getUint256FromItem(item) diff --git a/pkg/core/native/management.go b/pkg/core/native/management.go index 6ed98cd97..0f98cdba7 100644 --- a/pkg/core/native/management.go +++ b/pkg/core/native/management.go @@ -25,7 +25,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Management is contract-managing native contract. +// Management is a contract-managing native contract. type Management struct { interop.ContractMD NEO *NEO @@ -84,12 +84,12 @@ func (c *ManagementCache) Copy() dao.NativeContractCache { return cp } -// MakeContractKey creates a key from account script hash. +// MakeContractKey creates a key from the account script hash. func MakeContractKey(h util.Uint160) []byte { return makeUint160Key(prefixContract, h) } -// newManagement creates new Management native contract. +// newManagement creates a new Management native contract. func newManagement() *Management { var m = &Management{ ContractMD: *interop.NewContractMD(nativenames.Management, ManagementContractID), @@ -168,7 +168,7 @@ func (m *Management) getContract(ic *interop.Context, args []stackitem.Item) sta return contractToStack(ctr) } -// GetContract returns contract with given hash from given DAO. +// GetContract returns a contract with the given hash from the given DAO. func (m *Management) GetContract(d *dao.Simple, hash util.Uint160) (*state.Contract, error) { cache := d.GetROCache(m.ID).(*ManagementCache) cs, ok := cache.contracts[hash] @@ -198,7 +198,7 @@ func getLimitedSlice(arg stackitem.Item, max int) ([]byte, error) { } // getNefAndManifestFromItems converts input arguments into NEF and manifest -// adding appropriate deployment GAS price and sanitizing inputs. +// adding an appropriate deployment GAS price and sanitizing inputs. func (m *Management) getNefAndManifestFromItems(ic *interop.Context, args []stackitem.Item, isDeploy bool) (*nef.File, *manifest.Manifest, error) { nefBytes, err := getLimitedSlice(args[0], math.MaxInt32) // Upper limits are checked during NEF deserialization. if err != nil { @@ -282,7 +282,7 @@ func (m *Management) markUpdated(d *dao.Simple, hash util.Uint160, cs *state.Con updateContractCache(cache, cs) } -// Deploy creates contract's hash/ID and saves new contract into the given DAO. +// Deploy creates a contract's hash/ID and saves a new contract into the given DAO. // It doesn't run _deploy method and doesn't emit notification. func (m *Management) Deploy(d *dao.Simple, sender util.Uint160, neff *nef.File, manif *manifest.Manifest) (*state.Contract, error) { h := state.CreateContractHash(sender, neff.Checksum, manif.Name) @@ -390,7 +390,7 @@ func (m *Management) destroy(ic *interop.Context, sis []stackitem.Item) stackite return stackitem.Null{} } -// Destroy drops given contract from DAO along with its storage. It doesn't emit notification. +// Destroy drops the given contract from DAO along with its storage. It doesn't emit notification. func (m *Management) Destroy(d *dao.Simple, hash util.Uint160) error { contract, err := m.GetContract(d, hash) if err != nil { @@ -448,12 +448,12 @@ func contractToStack(cs *state.Contract) stackitem.Item { return si } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (m *Management) Metadata() *interop.ContractMD { return &m.ContractMD } -// updateContractCache saves contract in the common and NEP-related caches. It's +// updateContractCache saves the contract in the common and NEP-related caches. It's // an internal method that must be called with m.mtx lock taken. func updateContractCache(cache *ManagementCache, cs *state.Contract) { cache.contracts[cs.Hash] = cs @@ -465,7 +465,7 @@ func updateContractCache(cache *ManagementCache, cs *state.Contract) { } } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (m *Management) OnPersist(ic *interop.Context) error { var cache *ManagementCache for _, native := range ic.Natives { @@ -495,7 +495,7 @@ func (m *Management) OnPersist(ic *interop.Context) error { } // InitializeCache initializes contract cache with the proper values from storage. -// Cache initialisation should be done apart from Initialize because Initialize is +// Cache initialization should be done apart from Initialize because Initialize is // called only when deploying native contracts. func (m *Management) InitializeCache(d *dao.Simple) error { cache := &ManagementCache{ @@ -521,7 +521,7 @@ func (m *Management) InitializeCache(d *dao.Simple) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (m *Management) PostPersist(ic *interop.Context) error { return nil } @@ -550,7 +550,7 @@ func (m *Management) GetNEP17Contracts(d *dao.Simple) []util.Uint160 { return result } -// Initialize implements Contract interface. +// Initialize implements the Contract interface. func (m *Management) Initialize(ic *interop.Context) error { setIntWithKey(m.ID, ic.DAO, keyMinimumDeploymentFee, defaultMinimumDeploymentFee) setIntWithKey(m.ID, ic.DAO, keyNextAvailableID, 1) diff --git a/pkg/core/native/native_gas.go b/pkg/core/native/native_gas.go index 14e83694c..e8c3e889b 100644 --- a/pkg/core/native/native_gas.go +++ b/pkg/core/native/native_gas.go @@ -82,7 +82,7 @@ func (g *GAS) balanceFromBytes(si *state.StorageItem) (*big.Int, error) { return &acc.Balance, err } -// Initialize initializes GAS contract. +// Initialize initializes a GAS contract. func (g *GAS) Initialize(ic *interop.Context) error { if err := g.nep17TokenNative.Initialize(ic); err != nil { return err @@ -99,7 +99,7 @@ func (g *GAS) Initialize(ic *interop.Context) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (g *GAS) OnPersist(ic *interop.Context) error { if len(ic.Block.Transactions) == 0 { return nil @@ -127,7 +127,7 @@ func (g *GAS) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (g *GAS) PostPersist(ic *interop.Context) error { return nil } diff --git a/pkg/core/native/native_neo.go b/pkg/core/native/native_neo.go index 84f66bee0..31e41b0f2 100644 --- a/pkg/core/native/native_neo.go +++ b/pkg/core/native/native_neo.go @@ -52,13 +52,13 @@ type NeoCache struct { // committee contains cached committee members and their votes. // It is updated once in a while depending on committee size // (every 28 blocks for mainnet). It's value - // is always equal to value stored by `prefixCommittee`. + // is always equal to the value stored by `prefixCommittee`. committee keysWithVotes - // committeeHash contains script hash of the committee. + // committeeHash contains the script hash of the committee. committeeHash util.Uint160 - // gasPerVoteCache contains last updated value of GAS per vote reward for candidates. - // It is set in state-modifying methods only and read in `PostPersist` thus is not protected + // gasPerVoteCache contains the last updated value of GAS per vote reward for candidates. + // It is set in state-modifying methods only and read in `PostPersist`, thus is not protected // by any mutex. gasPerVoteCache map[string]big.Int } @@ -67,7 +67,7 @@ const ( neoContractID = -5 // NEOTotalSupply is the total amount of NEO in the system. NEOTotalSupply = 100000000 - // DefaultRegisterPrice is default price for candidate register. + // DefaultRegisterPrice is the default price for candidate register. DefaultRegisterPrice = 1000 * GASFactor // prefixCandidate is a prefix used to store validator's data. prefixCandidate = 33 @@ -139,7 +139,7 @@ func copyNeoCache(src, dst *NeoCache) { } } -// makeValidatorKey creates a key from account script hash. +// makeValidatorKey creates a key from the account script hash. func makeValidatorKey(key *keys.PublicKey) []byte { b := key.Bytes() // Don't create a new buffer. @@ -228,7 +228,7 @@ func newNEO(cfg config.ProtocolConfiguration) *NEO { return n } -// Initialize initializes NEO contract. +// Initialize initializes a NEO contract. func (n *NEO) Initialize(ic *interop.Context) error { if err := n.nep17TokenNative.Initialize(ic); err != nil { return err @@ -276,8 +276,8 @@ func (n *NEO) Initialize(ic *interop.Context) error { return nil } -// InitializeCache initializes all NEO cache with the proper values from storage. -// Cache initialisation should be done apart from Initialize because Initialize is +// InitializeCache initializes all NEO cache with the proper values from the storage. +// Cache initialization should be done apart from Initialize because Initialize is // called only when deploying native contracts. func (n *NEO) InitializeCache(blockHeight uint32, d *dao.Simple) error { cache := &NeoCache{ @@ -344,7 +344,7 @@ func (n *NEO) updateCommittee(cache *NeoCache, ic *interop.Context) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (n *NEO) OnPersist(ic *interop.Context) error { if n.cfg.ShouldUpdateCommitteeAt(ic.Block.Index) { cache := ic.DAO.GetRWCache(n.ID).(*NeoCache) @@ -361,7 +361,7 @@ func (n *NEO) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (n *NEO) PostPersist(ic *interop.Context) error { gas := n.GetGASPerBlock(ic.DAO, ic.Block.Index) cache := ic.DAO.GetROCache(n.ID).(*NeoCache) diff --git a/pkg/core/native/native_neo_candidate.go b/pkg/core/native/native_neo_candidate.go index 8a1d6ca84..068d6dde5 100644 --- a/pkg/core/native/native_neo_candidate.go +++ b/pkg/core/native/native_neo_candidate.go @@ -11,7 +11,7 @@ type candidate struct { Votes big.Int } -// FromBytes unmarshals candidate from byte array. +// FromBytes unmarshals a candidate from the byte array. func (c *candidate) FromBytes(data []byte) *candidate { err := stackitem.DeserializeConvertible(data, c) if err != nil { diff --git a/pkg/core/native/native_nep17.go b/pkg/core/native/native_nep17.go index 021364b5d..c28c524ac 100644 --- a/pkg/core/native/native_nep17.go +++ b/pkg/core/native/native_nep17.go @@ -22,12 +22,12 @@ import ( // prefixAccount is the standard prefix used to store account data. const prefixAccount = 20 -// makeAccountKey creates a key from account script hash. +// makeAccountKey creates a key from the account script hash. func makeAccountKey(h util.Uint160) []byte { return makeUint160Key(prefixAccount, h) } -// nep17TokenNative represents NEP-17 token contract. +// nep17TokenNative represents a NEP-17 token contract. type nep17TokenNative struct { interop.ContractMD symbol string @@ -165,8 +165,8 @@ func (c *nep17TokenNative) emitTransfer(ic *interop.Context, from, to *util.Uint ic.Notifications = append(ic.Notifications, ne) } -// updateAccBalance adds specified amount to the acc's balance. If requiredBalance -// is set and amount is 0, then acc's balance is checked against requiredBalance. +// updateAccBalance adds the specified amount to the acc's balance. If requiredBalance +// is set and amount is 0, the acc's balance is checked against requiredBalance. func (c *nep17TokenNative) updateAccBalance(ic *interop.Context, acc util.Uint160, amount *big.Int, requiredBalance *big.Int) error { key := makeAccountKey(acc) si := ic.DAO.GetStorageItem(c.ID, key) @@ -175,7 +175,7 @@ func (c *nep17TokenNative) updateAccBalance(ic *interop.Context, acc util.Uint16 return errors.New("insufficient funds") } if amount.Sign() == 0 { - // it's OK to transfer 0 if the balance 0, no need to put si to the storage + // it's OK to transfer 0 if the balance is 0, no need to put si to the storage return nil } si = state.StorageItem{} @@ -196,7 +196,7 @@ func (c *nep17TokenNative) updateAccBalance(ic *interop.Context, acc util.Uint16 return nil } -// TransferInternal transfers NEO between accounts. +// TransferInternal transfers NEO across accounts. func (c *nep17TokenNative) TransferInternal(ic *interop.Context, from, to util.Uint160, amount *big.Int, data stackitem.Item) error { if amount.Sign() == -1 { return errors.New("negative amount") diff --git a/pkg/core/native/native_test/neo_test.go b/pkg/core/native/native_test/neo_test.go index 9314efd45..a68be75cf 100644 --- a/pkg/core/native/native_test/neo_test.go +++ b/pkg/core/native/native_test/neo_test.go @@ -78,7 +78,7 @@ func TestNEO_Vote(t *testing.T) { require.NoError(t, err) require.Equal(t, standBySorted, keys.PublicKeys(pubs)) - // voters vote for candidates. The aim of this test is to check that voting + // voters vote for candidates. The aim of this test is to check if voting // reward is proportional to the NEO balance. voters := make([]neotest.Signer, committeeSize+1) // referenceAccounts perform the same actions as voters except voting, i.e. we diff --git a/pkg/core/native/native_test/oracle_test.go b/pkg/core/native/native_test/oracle_test.go index 1542d6813..4aafc7175 100644 --- a/pkg/core/native/native_test/oracle_test.go +++ b/pkg/core/native/native_test/oracle_test.go @@ -136,8 +136,8 @@ func TestOracle_Request(t *testing.T) { stackitem.NewByteArray(tx.Attributes[0].Value.(*transaction.OracleResponse).Result), }), actual) - // Check that processed request is removed. We can't access GetRequestInternal directly, - // but adding response to this request should fail due to invalid request error. + // Check that the processed request is removed. We can't access GetRequestInternal directly, + // but adding a response to this request should fail due to invalid request error. tx = prepareResponseTx(t, 0) err = e.Chain.VerifyTx(tx) require.Error(t, err) @@ -149,8 +149,8 @@ func TestOracle_Request(t *testing.T) { e.AddNewBlock(t, tx) e.CheckFault(t, tx.Hash(), "ABORT") - // Check that processed request is cleaned up even if callback failed. We can't - // access GetRequestInternal directly, but adding response to this request + // Check that the processed request is cleaned up even if callback failed. We can't + // access GetRequestInternal directly, but adding a response to this request // should fail due to invalid request error. tx = prepareResponseTx(t, 1) err = e.Chain.VerifyTx(tx) diff --git a/pkg/core/native/nativenames/names.go b/pkg/core/native/nativenames/names.go index 65c03c0d1..3ddb814a0 100644 --- a/pkg/core/native/nativenames/names.go +++ b/pkg/core/native/nativenames/names.go @@ -14,7 +14,7 @@ const ( StdLib = "StdLib" ) -// IsValid checks that name is a valid native contract's name. +// IsValid checks if the name is a valid native contract's name. func IsValid(name string) bool { return name == Management || name == Ledger || diff --git a/pkg/core/native/nativenames_test.go b/pkg/core/native/nativenames_test.go index b710f09be..df0be1eba 100644 --- a/pkg/core/native/nativenames_test.go +++ b/pkg/core/native/nativenames_test.go @@ -10,7 +10,7 @@ import ( ) func TestNativenamesIsValid(t *testing.T) { - // test that all native names has been added to IsValid + // test that all native names have been added to IsValid cfg := config.ProtocolConfiguration{P2PSigExtensions: true} contracts := NewContracts(cfg) for _, c := range contracts.Contracts { diff --git a/pkg/core/native/neo_types.go b/pkg/core/native/neo_types.go index 21e5dfb3b..7c27e45bc 100644 --- a/pkg/core/native/neo_types.go +++ b/pkg/core/native/neo_types.go @@ -9,14 +9,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// gasIndexPair contains block index together with generated gas per block. +// gasIndexPair contains the block index together with the generated gas per block. // It is used to cache NEO GASRecords. type gasIndexPair struct { Index uint32 GASPerBlock big.Int } -// gasRecord contains history of gas per block changes. It is used only by NEO cache. +// gasRecord contains the history of gas per block changes. It is used only by NEO cache. type gasRecord []gasIndexPair type ( @@ -33,7 +33,7 @@ type ( keysWithVotes []keyWithVotes ) -// PublicKey unmarshals and returns public key of k. +// PublicKey unmarshals and returns the public key of k. func (k keyWithVotes) PublicKey() (*keys.PublicKey, error) { if k.UnmarshaledKey != nil { return k.UnmarshaledKey, nil diff --git a/pkg/core/native/noderoles/roles.go b/pkg/core/native/noderoles/roles.go index 3a0572fe2..e9bf43404 100644 --- a/pkg/core/native/noderoles/roles.go +++ b/pkg/core/native/noderoles/roles.go @@ -1,6 +1,6 @@ package noderoles -// Role represents type of participant. +// Role represents the type of the participant. type Role byte // Role enumeration. diff --git a/pkg/core/native/notary.go b/pkg/core/native/notary.go index 2d5ab29ec..f53bc7346 100644 --- a/pkg/core/native/notary.go +++ b/pkg/core/native/notary.go @@ -128,12 +128,12 @@ func newNotary() *Notary { return n } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (n *Notary) Metadata() *interop.ContractMD { return &n.ContractMD } -// Initialize initializes Notary native contract and implements Contract interface. +// Initialize initializes Notary native contract and implements the Contract interface. func (n *Notary) Initialize(ic *interop.Context) error { setIntWithKey(n.ID, ic.DAO, maxNotValidBeforeDeltaKey, defaultMaxNotValidBeforeDelta) setIntWithKey(n.ID, ic.DAO, notaryServiceFeeKey, defaultNotaryServiceFeePerKey) @@ -156,7 +156,7 @@ func (n *Notary) InitializeCache(d *dao.Simple) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (n *Notary) OnPersist(ic *interop.Context) error { var ( nFees int64 @@ -199,12 +199,12 @@ func (n *Notary) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (n *Notary) PostPersist(ic *interop.Context) error { return nil } -// onPayment records deposited amount as belonging to "from" address with a lock +// onPayment records the deposited amount as belonging to "from" address with a lock // till the specified chain's height. func (n *Notary) onPayment(ic *interop.Context, args []stackitem.Item) stackitem.Item { if h := ic.VM.GetCallingScriptHash(); h != n.GAS.Hash { @@ -255,7 +255,7 @@ func (n *Notary) onPayment(ic *interop.Context, args []stackitem.Item) stackitem return stackitem.Null{} } -// lockDepositUntil updates the chain's height until which deposit is locked. +// lockDepositUntil updates the chain's height until which the deposit is locked. func (n *Notary) lockDepositUntil(ic *interop.Context, args []stackitem.Item) stackitem.Item { addr := toUint160(args[0]) ok, err := runtime.CheckHashedWitness(ic, addr) @@ -321,7 +321,7 @@ func (n *Notary) withdraw(ic *interop.Context, args []stackitem.Item) stackitem. return stackitem.NewBool(true) } -// balanceOf returns deposited GAS amount for specified address. +// balanceOf returns the deposited GAS amount for the specified address. func (n *Notary) balanceOf(ic *interop.Context, args []stackitem.Item) stackitem.Item { acc := toUint160(args[0]) return stackitem.NewBigInteger(n.BalanceOf(ic.DAO, acc)) @@ -336,7 +336,7 @@ func (n *Notary) BalanceOf(dao *dao.Simple, acc util.Uint160) *big.Int { return deposit.Amount } -// expirationOf Returns deposit lock height for specified address. +// expirationOf returns the deposit lock height for the specified address. func (n *Notary) expirationOf(ic *interop.Context, args []stackitem.Item) stackitem.Item { acc := toUint160(args[0]) return stackitem.Make(n.ExpirationOf(ic.DAO, acc)) @@ -400,7 +400,7 @@ func (n *Notary) GetNotaryNodes(d *dao.Simple) (keys.PublicKeys, error) { return nodes, err } -// getMaxNotValidBeforeDelta is Notary contract method and returns the maximum NotValidBefore delta. +// getMaxNotValidBeforeDelta is a Notary contract method and returns the maximum NotValidBefore delta. func (n *Notary) getMaxNotValidBeforeDelta(ic *interop.Context, _ []stackitem.Item) stackitem.Item { return stackitem.NewBigInteger(big.NewInt(int64(n.GetMaxNotValidBeforeDelta(ic.DAO)))) } @@ -411,7 +411,7 @@ func (n *Notary) GetMaxNotValidBeforeDelta(dao *dao.Simple) uint32 { return cache.maxNotValidBeforeDelta } -// setMaxNotValidBeforeDelta is Notary contract method and sets the maximum NotValidBefore delta. +// setMaxNotValidBeforeDelta is a Notary contract method and sets the maximum NotValidBefore delta. func (n *Notary) setMaxNotValidBeforeDelta(ic *interop.Context, args []stackitem.Item) stackitem.Item { value := toUint32(args[0]) cfg := ic.Chain.GetConfig() @@ -428,7 +428,7 @@ func (n *Notary) setMaxNotValidBeforeDelta(ic *interop.Context, args []stackitem return stackitem.Null{} } -// getNotaryServiceFeePerKey is Notary contract method and returns a reward per notary request key for notary nodes. +// getNotaryServiceFeePerKey is a Notary contract method and returns a reward per notary request key for notary nodes. func (n *Notary) getNotaryServiceFeePerKey(ic *interop.Context, _ []stackitem.Item) stackitem.Item { return stackitem.NewBigInteger(big.NewInt(int64(n.GetNotaryServiceFeePerKey(ic.DAO)))) } @@ -439,7 +439,7 @@ func (n *Notary) GetNotaryServiceFeePerKey(dao *dao.Simple) int64 { return cache.notaryServiceFeePerKey } -// setNotaryServiceFeePerKey is Notary contract method and sets a reward per notary request key for notary nodes. +// setNotaryServiceFeePerKey is a Notary contract method and sets a reward per notary request key for notary nodes. func (n *Notary) setNotaryServiceFeePerKey(ic *interop.Context, args []stackitem.Item) stackitem.Item { value := toInt64(args[0]) if value < 0 { @@ -454,8 +454,8 @@ func (n *Notary) setNotaryServiceFeePerKey(ic *interop.Context, args []stackitem return stackitem.Null{} } -// GetDepositFor returns state.Deposit for the account specified. It returns nil in case if -// deposit is not found in storage and panics in case of any other error. +// GetDepositFor returns state.Deposit for the account specified. It returns nil in case +// the deposit is not found in the storage and panics in case of any other error. func (n *Notary) GetDepositFor(dao *dao.Simple, acc util.Uint160) *state.Deposit { key := append([]byte{prefixDeposit}, acc.BytesBE()...) deposit := new(state.Deposit) @@ -469,13 +469,13 @@ func (n *Notary) GetDepositFor(dao *dao.Simple, acc util.Uint160) *state.Deposit panic(fmt.Errorf("failed to get deposit for %s from storage: %w", acc.StringBE(), err)) } -// putDepositFor puts deposit on the balance of the specified account in the storage. +// putDepositFor puts the deposit on the balance of the specified account in the storage. func (n *Notary) putDepositFor(dao *dao.Simple, deposit *state.Deposit, acc util.Uint160) error { key := append([]byte{prefixDeposit}, acc.BytesBE()...) return putConvertibleToDAO(n.ID, dao, key, deposit) } -// removeDepositFor removes deposit from the storage. +// removeDepositFor removes the deposit from the storage. func (n *Notary) removeDepositFor(dao *dao.Simple, acc util.Uint160) { key := append([]byte{prefixDeposit}, acc.BytesBE()...) dao.DeleteStorageItem(n.ID, key) diff --git a/pkg/core/native/oracle.go b/pkg/core/native/oracle.go index 7b3914b5c..380f45e76 100644 --- a/pkg/core/native/oracle.go +++ b/pkg/core/native/oracle.go @@ -42,7 +42,7 @@ type Oracle struct { // Module is an oracle module capable of talking with the external world. Module atomic.Value - // newRequests contains new requests created during current block. + // newRequests contains new requests created during the current block. newRequests map[uint64]*state.OracleRequest } @@ -59,10 +59,10 @@ const ( // maxRequestsCount is the maximum number of requests per URL. maxRequestsCount = 256 - // DefaultOracleRequestPrice is default amount GAS needed for oracle request. + // DefaultOracleRequestPrice is the default amount GAS needed for an oracle request. DefaultOracleRequestPrice = 5000_0000 - // MinimumResponseGas is the minimum response fee permitted for request. + // MinimumResponseGas is the minimum response fee permitted for a request. MinimumResponseGas = 10_000_000 ) @@ -141,12 +141,12 @@ func newOracle() *Oracle { return o } -// GetOracleResponseScript returns script for transaction with oracle response. +// GetOracleResponseScript returns a script for the transaction with an oracle response. func (o *Oracle) GetOracleResponseScript() []byte { return slice.Copy(o.oracleScript) } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (o *Oracle) OnPersist(ic *interop.Context) error { var err error if o.newRequests == nil { @@ -227,7 +227,7 @@ func (o *Oracle) Metadata() *interop.ContractMD { return &o.ContractMD } -// Initialize initializes Oracle contract. +// Initialize initializes an Oracle contract. func (o *Oracle) Initialize(ic *interop.Context) error { setIntWithKey(o.ID, ic.DAO, prefixRequestID, 0) setIntWithKey(o.ID, ic.DAO, prefixRequestPrice, DefaultOracleRequestPrice) @@ -262,7 +262,7 @@ func (o *Oracle) finish(ic *interop.Context, _ []stackitem.Item) stackitem.Item return stackitem.Null{} } -// FinishInternal processes oracle response. +// FinishInternal processes an oracle response. func (o *Oracle) FinishInternal(ic *interop.Context) error { resp := getResponse(ic.Tx) if resp == nil { @@ -338,7 +338,7 @@ func (o *Oracle) request(ic *interop.Context, args []stackitem.Item) stackitem.I return stackitem.Null{} } -// RequestInternal processes oracle request. +// RequestInternal processes an oracle request. func (o *Oracle) RequestInternal(ic *interop.Context, url string, filter *string, cb string, userData stackitem.Item, gas *big.Int) error { if len(url) > maxURLLength || (filter != nil && len(*filter) > maxFilterLength) || len(cb) > maxCallbackLength || !gas.IsInt64() { return ErrBigArgument @@ -362,7 +362,7 @@ func (o *Oracle) RequestInternal(ic *interop.Context, url string, filter *string si = bigint.ToPreallocatedBytes(itemID, si) ic.DAO.PutStorageItem(o.ID, prefixRequestID, si) - // Should be executed from contract. + // Should be executed from the contract. _, err := ic.GetContract(ic.VM.GetCallingScriptHash()) if err != nil { return err @@ -404,7 +404,7 @@ func (o *Oracle) RequestInternal(ic *interop.Context, url string, filter *string return o.PutRequestInternal(id, req, ic.DAO) } -// PutRequestInternal puts oracle request with the specified id to d. +// PutRequestInternal puts the oracle request with the specified id to d. func (o *Oracle) PutRequestInternal(id uint64, req *state.OracleRequest, d *dao.Simple) error { reqKey := makeRequestKey(id) if err := putConvertibleToDAO(o.ID, d, reqKey, req); err != nil { @@ -425,7 +425,7 @@ func (o *Oracle) PutRequestInternal(id uint64, req *state.OracleRequest, d *dao. return putConvertibleToDAO(o.ID, d, key, lst) } -// GetScriptHash returns script hash or oracle nodes. +// GetScriptHash returns script hash of oracle nodes. func (o *Oracle) GetScriptHash(d *dao.Simple) (util.Uint160, error) { return o.Desig.GetLastDesignatedHash(d, noderoles.Oracle) } @@ -436,14 +436,14 @@ func (o *Oracle) GetOracleNodes(d *dao.Simple) (keys.PublicKeys, error) { return nodes, err } -// GetRequestInternal returns request by ID and key under which it is stored. +// GetRequestInternal returns the request by ID and key under which it is stored. func (o *Oracle) GetRequestInternal(d *dao.Simple, id uint64) (*state.OracleRequest, error) { key := makeRequestKey(id) req := new(state.OracleRequest) return req, o.getConvertibleFromDAO(d, key, req) } -// GetIDListInternal returns request by ID and key under which it is stored. +// GetIDListInternal returns the request by ID and key under which it is stored. func (o *Oracle) GetIDListInternal(d *dao.Simple, url string) (*IDList, error) { key := makeIDListKey(url) idList := new(IDList) @@ -546,7 +546,7 @@ func (o *Oracle) updateCache(d *dao.Simple) error { return nil } -// CreateOracleResponseScript returns script that is used to create native Oracle +// CreateOracleResponseScript returns a script that is used to create the native Oracle // response. func CreateOracleResponseScript(nativeOracleHash util.Uint160) []byte { w := io.NewBufBinWriter() diff --git a/pkg/core/native/oracle_types.go b/pkg/core/native/oracle_types.go index b678f67db..ae5c8c6cd 100644 --- a/pkg/core/native/oracle_types.go +++ b/pkg/core/native/oracle_types.go @@ -12,7 +12,7 @@ import ( // IDList is a list of oracle request IDs. type IDList []uint64 -// NodeList represents list or oracle nodes. +// NodeList represents a list of oracle nodes. type NodeList keys.PublicKeys // ToStackItem implements stackitem.Convertible. It never returns an error. @@ -41,7 +41,7 @@ func (l *IDList) FromStackItem(it stackitem.Item) error { return nil } -// Remove removes id from list. +// Remove removes id from the list. func (l *IDList) Remove(id uint64) bool { for i := range *l { if id == (*l)[i] { diff --git a/pkg/core/native/policy.go b/pkg/core/native/policy.go index 9dd40876d..17bc0f34e 100644 --- a/pkg/core/native/policy.go +++ b/pkg/core/native/policy.go @@ -130,12 +130,12 @@ func newPolicy() *Policy { return p } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (p *Policy) Metadata() *interop.ContractMD { return &p.ContractMD } -// Initialize initializes Policy native contract and implements Contract interface. +// Initialize initializes Policy native contract and implements the Contract interface. func (p *Policy) Initialize(ic *interop.Context) error { setIntWithKey(p.ID, ic.DAO, feePerByteKey, defaultFeePerByte) setIntWithKey(p.ID, ic.DAO, execFeeFactorKey, defaultExecFeeFactor) @@ -196,7 +196,7 @@ func (p *Policy) PostPersist(ic *interop.Context) error { return nil } -// getFeePerByte is Policy contract method and returns required transaction's fee +// getFeePerByte is a Policy contract method that returns the required transaction's fee // per byte. func (p *Policy) getFeePerByte(ic *interop.Context, _ []stackitem.Item) stackitem.Item { return stackitem.NewBigInteger(big.NewInt(p.GetFeePerByteInternal(ic.DAO))) @@ -208,7 +208,7 @@ func (p *Policy) GetFeePerByteInternal(dao *dao.Simple) int64 { return cache.feePerByte } -// GetMaxVerificationGas returns maximum gas allowed to be burned during verificaion. +// GetMaxVerificationGas returns the maximum gas allowed to be burned during verification. func (p *Policy) GetMaxVerificationGas(dao *dao.Simple) int64 { cache := dao.GetROCache(p.ID).(*PolicyCache) return cache.maxVerificationGas @@ -238,7 +238,7 @@ func (p *Policy) setExecFeeFactor(ic *interop.Context, args []stackitem.Item) st return stackitem.Null{} } -// isBlocked is Policy contract method and checks whether provided account is blocked. +// isBlocked is Policy contract method that checks whether provided account is blocked. func (p *Policy) isBlocked(ic *interop.Context, args []stackitem.Item) stackitem.Item { hash := toUint160(args[0]) _, blocked := p.isBlockedInternal(ic.DAO, hash) @@ -290,7 +290,7 @@ func (p *Policy) setStoragePrice(ic *interop.Context, args []stackitem.Item) sta return stackitem.Null{} } -// setFeePerByte is Policy contract method and sets transaction's fee per byte. +// setFeePerByte is a Policy contract method that sets transaction's fee per byte. func (p *Policy) setFeePerByte(ic *interop.Context, args []stackitem.Item) stackitem.Item { value := toBigInt(args[0]).Int64() if value < 0 || value > maxFeePerByte { @@ -305,7 +305,7 @@ func (p *Policy) setFeePerByte(ic *interop.Context, args []stackitem.Item) stack return stackitem.Null{} } -// blockAccount is Policy contract method and adds given account hash to the list +// blockAccount is a Policy contract method that adds the given account hash to the list // of blocked accounts. func (p *Policy) blockAccount(ic *interop.Context, args []stackitem.Item) stackitem.Item { if !p.NEO.checkCommittee(ic) { @@ -333,7 +333,7 @@ func (p *Policy) blockAccount(ic *interop.Context, args []stackitem.Item) stacki return stackitem.NewBool(true) } -// unblockAccount is Policy contract method and removes given account hash from +// unblockAccount is a Policy contract method that removes the given account hash from // the list of blocked accounts. func (p *Policy) unblockAccount(ic *interop.Context, args []stackitem.Item) stackitem.Item { if !p.NEO.checkCommittee(ic) { @@ -351,8 +351,8 @@ func (p *Policy) unblockAccount(ic *interop.Context, args []stackitem.Item) stac return stackitem.NewBool(true) } -// CheckPolicy checks whether transaction conforms to current policy restrictions -// like not being signed by blocked account or not exceeding block-level system +// CheckPolicy checks whether a transaction conforms to the current policy restrictions, +// like not being signed by a blocked account or not exceeding the block-level system // fee limit. func (p *Policy) CheckPolicy(d *dao.Simple, tx *transaction.Transaction) error { for _, signer := range tx.Signers { diff --git a/pkg/core/native/std.go b/pkg/core/native/std.go index 26fc49115..eecd58bf2 100644 --- a/pkg/core/native/std.go +++ b/pkg/core/native/std.go @@ -20,7 +20,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Std represents StdLib contract. +// Std represents an StdLib contract. type Std struct { interop.ContractMD } @@ -33,11 +33,11 @@ const ( ) var ( - // ErrInvalidBase is returned when base is invalid. + // ErrInvalidBase is returned when the base is invalid. ErrInvalidBase = errors.New("invalid base") - // ErrInvalidFormat is returned when string is not a number. + // ErrInvalidFormat is returned when the string is not a number. ErrInvalidFormat = errors.New("invalid format") - // ErrTooBigInput is returned when input exceeds size limit. + // ErrTooBigInput is returned when the input exceeds the size limit. ErrTooBigInput = errors.New("input is too big") ) @@ -420,22 +420,22 @@ func (s *Std) stringSplitAux(str, sep string, removeEmpty bool) []stackitem.Item return result } -// Metadata implements Contract interface. +// Metadata implements the Contract interface. func (s *Std) Metadata() *interop.ContractMD { return &s.ContractMD } -// Initialize implements Contract interface. +// Initialize implements the Contract interface. func (s *Std) Initialize(ic *interop.Context) error { return nil } -// OnPersist implements Contract interface. +// OnPersist implements the Contract interface. func (s *Std) OnPersist(ic *interop.Context) error { return nil } -// PostPersist implements Contract interface. +// PostPersist implements the Contract interface. func (s *Std) PostPersist(ic *interop.Context) error { return nil } diff --git a/pkg/core/native/util.go b/pkg/core/native/util.go index b75b40963..38fe03eee 100644 --- a/pkg/core/native/util.go +++ b/pkg/core/native/util.go @@ -44,7 +44,7 @@ func getIntWithKey(id int32, dao *dao.Simple, key []byte) int64 { return bigint.FromBytes(si).Int64() } -// makeUint160Key creates a key from account script hash. +// makeUint160Key creates a key from the account script hash. func makeUint160Key(prefix byte, h util.Uint160) []byte { k := make([]byte, util.Uint160Size+1) k[0] = prefix diff --git a/pkg/core/oracle_test.go b/pkg/core/oracle_test.go index 5529c39ca..6a6decd8a 100644 --- a/pkg/core/oracle_test.go +++ b/pkg/core/oracle_test.go @@ -477,7 +477,7 @@ type ( } ) -// Get implements oracle.HTTPClient interface. +// Get implements the oracle.HTTPClient interface. func (c *httpClient) Do(req *http.Request) (*http.Response, error) { if c.returnOracleRedirectionErrOn != nil && c.returnOracleRedirectionErrOn(req.URL.String()) { return nil, fmt.Errorf("%w: private network", oracle.ErrRestrictedRedirect) diff --git a/pkg/core/state/contract.go b/pkg/core/state/contract.go index 9d7cf8514..4bc5df70a 100644 --- a/pkg/core/state/contract.go +++ b/pkg/core/state/contract.go @@ -21,7 +21,7 @@ type Contract struct { UpdateCounter uint16 `json:"updatecounter"` } -// ContractBase represents part shared by native and user-deployed contracts. +// ContractBase represents a part shared by native and user-deployed contracts. type ContractBase struct { ID int32 `json:"id"` Hash util.Uint160 `json:"hash"` @@ -29,7 +29,7 @@ type ContractBase struct { Manifest manifest.Manifest `json:"manifest"` } -// NativeContract holds information about native contract. +// NativeContract holds information about the native contract. type NativeContract struct { ContractBase UpdateHistory []uint32 `json:"updatehistory"` @@ -54,7 +54,7 @@ func (c *Contract) ToStackItem() (stackitem.Item, error) { }), nil } -// FromStackItem fills Contract's data from given stack itemized contract +// FromStackItem fills Contract's data from the given stack itemized contract // representation. func (c *Contract) FromStackItem(item stackitem.Item) error { arr, ok := item.Value().([]stackitem.Item) @@ -102,8 +102,8 @@ func (c *Contract) FromStackItem(item stackitem.Item) error { return nil } -// CreateContractHash creates deployed contract hash from transaction sender -// and contract script. +// CreateContractHash creates a deployed contract hash from the transaction sender +// and the contract script. func CreateContractHash(sender util.Uint160, checksum uint32, name string) util.Uint160 { w := io.NewBufBinWriter() emit.Opcodes(w.BinWriter, opcode.ABORT) diff --git a/pkg/core/state/deposit.go b/pkg/core/state/deposit.go index 59c97fe54..3330031f7 100644 --- a/pkg/core/state/deposit.go +++ b/pkg/core/state/deposit.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Deposit represents GAS deposit from Notary contract. +// Deposit represents GAS deposit from a Notary contract. type Deposit struct { Amount *big.Int Till uint32 diff --git a/pkg/core/state/mpt_root.go b/pkg/core/state/mpt_root.go index fa1d6b469..201cd1ae7 100644 --- a/pkg/core/state/mpt_root.go +++ b/pkg/core/state/mpt_root.go @@ -7,7 +7,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// MPTRoot represents storage state root together with sign info. +// MPTRoot represents the storage state root together with sign info. type MPTRoot struct { Version byte `json:"version"` Index uint32 `json:"index"` @@ -15,21 +15,21 @@ type MPTRoot struct { Witness []transaction.Witness `json:"witnesses"` } -// Hash returns hash of s. +// Hash returns the hash of s. func (s *MPTRoot) Hash() util.Uint256 { buf := io.NewBufBinWriter() s.EncodeBinaryUnsigned(buf.BinWriter) return hash.Sha256(buf.Bytes()) } -// DecodeBinaryUnsigned decodes hashable part of state root. +// DecodeBinaryUnsigned decodes the hashable part of the state root. func (s *MPTRoot) DecodeBinaryUnsigned(r *io.BinReader) { s.Version = r.ReadB() s.Index = r.ReadU32LE() s.Root.DecodeBinary(r) } -// EncodeBinaryUnsigned encodes hashable part of state root.. +// EncodeBinaryUnsigned encodes the hashable part of the state root. func (s *MPTRoot) EncodeBinaryUnsigned(w *io.BinWriter) { w.WriteB(s.Version) w.WriteU32LE(s.Index) diff --git a/pkg/core/state/native_state.go b/pkg/core/state/native_state.go index 22141a62f..0f255b01c 100644 --- a/pkg/core/state/native_state.go +++ b/pkg/core/state/native_state.go @@ -11,19 +11,19 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// NEP17Balance represents balance state of a NEP-17-token. +// NEP17Balance represents the balance state of a NEP-17-token. type NEP17Balance struct { Balance big.Int } -// NEOBalance represents balance state of a NEO-token. +// NEOBalance represents the balance state of a NEO-token. type NEOBalance struct { NEP17Balance BalanceHeight uint32 VoteTo *keys.PublicKey } -// NEP17BalanceFromBytes converts serialized NEP17Balance to structure. +// NEP17BalanceFromBytes converts the serialized NEP17Balance to a structure. func NEP17BalanceFromBytes(b []byte) (*NEP17Balance, error) { if len(b) < 4 { if len(b) == 0 { @@ -100,7 +100,7 @@ func (s *NEP17Balance) FromStackItem(item stackitem.Item) error { return nil } -// NEOBalanceFromBytes converts serialized NEOBalance to structure. +// NEOBalanceFromBytes converts the serialized NEOBalance to a structure. func NEOBalanceFromBytes(b []byte) (*NEOBalance, error) { balance := new(NEOBalance) err := balanceFromBytes(b, balance) @@ -110,7 +110,7 @@ func NEOBalanceFromBytes(b []byte) (*NEOBalance, error) { return balance, nil } -// Bytes returns serialized NEOBalance. +// Bytes returns a serialized NEOBalance. func (s *NEOBalance) Bytes() []byte { return balanceToBytes(s) } diff --git a/pkg/core/state/notification_event.go b/pkg/core/state/notification_event.go index c40f63e35..709d7d165 100644 --- a/pkg/core/state/notification_event.go +++ b/pkg/core/state/notification_event.go @@ -12,15 +12,15 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// NotificationEvent is a tuple of scripthash that emitted the Item as a -// notification and that item itself. +// NotificationEvent is a tuple of the scripthash that has emitted the Item as a +// notification and the item itself. type NotificationEvent struct { ScriptHash util.Uint160 `json:"contract"` Name string `json:"eventname"` Item *stackitem.Array `json:"state"` } -// AppExecResult represent the result of the script execution, gathering together +// AppExecResult represents the result of the script execution, gathering together // all resulting notifications, state, stack and other metadata. type AppExecResult struct { Container util.Uint256 @@ -100,7 +100,7 @@ type notificationEventAux struct { Item json.RawMessage `json:"state"` } -// MarshalJSON implements implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (ne NotificationEvent) MarshalJSON() ([]byte, error) { item, err := stackitem.ToJSONWithTypes(ne.Item) if err != nil { @@ -113,7 +113,7 @@ func (ne NotificationEvent) MarshalJSON() ([]byte, error) { }) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (ne *NotificationEvent) UnmarshalJSON(data []byte) error { aux := new(notificationEventAux) if err := json.Unmarshal(data, aux); err != nil { @@ -137,7 +137,7 @@ type appExecResultAux struct { Container util.Uint256 `json:"container"` } -// MarshalJSON implements implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (aer *AppExecResult) MarshalJSON() ([]byte, error) { h, err := json.Marshal(&appExecResultAux{ Container: aer.Container, @@ -158,7 +158,7 @@ func (aer *AppExecResult) MarshalJSON() ([]byte, error) { return h, nil } -// UnmarshalJSON implements implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (aer *AppExecResult) UnmarshalJSON(data []byte) error { aux := new(appExecResultAux) if err := json.Unmarshal(data, aux); err != nil { @@ -192,7 +192,7 @@ type executionAux struct { FaultException string `json:"exception,omitempty"` } -// MarshalJSON implements implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (e Execution) MarshalJSON() ([]byte, error) { arr := make([]json.RawMessage, len(e.Stack)) for i := range arr { @@ -216,7 +216,7 @@ func (e Execution) MarshalJSON() ([]byte, error) { }) } -// UnmarshalJSON implements implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (e *Execution) UnmarshalJSON(data []byte) error { aux := new(executionAux) if err := json.Unmarshal(data, aux); err != nil { diff --git a/pkg/core/state/oracle.go b/pkg/core/state/oracle.go index 861a5a1db..6a3c29dca 100644 --- a/pkg/core/state/oracle.go +++ b/pkg/core/state/oracle.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// OracleRequest represents oracle request. +// OracleRequest represents an oracle request. type OracleRequest struct { OriginalTxID util.Uint256 GasForResponse uint64 diff --git a/pkg/core/state/tokens.go b/pkg/core/state/tokens.go index 9470fa845..6faa69edc 100644 --- a/pkg/core/state/tokens.go +++ b/pkg/core/state/tokens.go @@ -45,8 +45,8 @@ type NEP11Transfer struct { ID []byte } -// TokenTransferInfo stores map of the contract IDs to the balance's last updated -// block trackers along with information about NEP-17 and NEP-11 transfer batch. +// TokenTransferInfo stores a map of the contract IDs to the balance's last updated +// block trackers along with the information about NEP-17 and NEP-11 transfer batch. type TokenTransferInfo struct { LastUpdated map[int32]uint32 // NextNEP11Batch stores the index of the next NEP-17 transfer batch. @@ -72,7 +72,7 @@ func NewTokenTransferInfo() *TokenTransferInfo { } } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (bs *TokenTransferInfo) DecodeBinary(r *io.BinReader) { bs.NextNEP11Batch = r.ReadU32LE() bs.NextNEP17Batch = r.ReadU32LE() @@ -89,7 +89,7 @@ func (bs *TokenTransferInfo) DecodeBinary(r *io.BinReader) { bs.LastUpdated = m } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (bs *TokenTransferInfo) EncodeBinary(w *io.BinWriter) { w.WriteU32LE(bs.NextNEP11Batch) w.WriteU32LE(bs.NextNEP17Batch) @@ -104,7 +104,7 @@ func (bs *TokenTransferInfo) EncodeBinary(w *io.BinWriter) { } } -// Append appends single transfer to a log. +// Append appends a single transfer to a log. func (lg *TokenTransferLog) Append(tr io.Serializable) error { // The first entry, set up counter. if len(lg.Raw) == 0 { @@ -123,7 +123,7 @@ func (lg *TokenTransferLog) Append(tr io.Serializable) error { return nil } -// ForEachNEP11 iterates over transfer log returning on first error. +// ForEachNEP11 iterates over a transfer log returning on the first error. func (lg *TokenTransferLog) ForEachNEP11(f func(*NEP11Transfer) (bool, error)) (bool, error) { if lg == nil || len(lg.Raw) == 0 { return true, nil @@ -145,7 +145,7 @@ func (lg *TokenTransferLog) ForEachNEP11(f func(*NEP11Transfer) (bool, error)) ( return true, nil } -// ForEachNEP17 iterates over transfer log returning on first error. +// ForEachNEP17 iterates over a transfer log returning on the first error. func (lg *TokenTransferLog) ForEachNEP17(f func(*NEP17Transfer) (bool, error)) (bool, error) { if lg == nil || len(lg.Raw) == 0 { return true, nil @@ -167,7 +167,7 @@ func (lg *TokenTransferLog) ForEachNEP17(f func(*NEP17Transfer) (bool, error)) ( return true, nil } -// Size returns an amount of transfer written in log. +// Size returns the amount of the transfer written in the log. func (lg *TokenTransferLog) Size() int { if len(lg.Raw) == 0 { return 0 @@ -175,7 +175,7 @@ func (lg *TokenTransferLog) Size() int { return int(lg.Raw[0]) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (t *NEP17Transfer) EncodeBinary(w *io.BinWriter) { w.WriteU32LE(uint32(t.Asset)) w.WriteBytes(t.Tx[:]) @@ -187,7 +187,7 @@ func (t *NEP17Transfer) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes(amount) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (t *NEP17Transfer) DecodeBinary(r *io.BinReader) { t.Asset = int32(r.ReadU32LE()) r.ReadBytes(t.Tx[:]) @@ -199,13 +199,13 @@ func (t *NEP17Transfer) DecodeBinary(r *io.BinReader) { t.Amount = *bigint.FromBytes(amount) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (t *NEP11Transfer) EncodeBinary(w *io.BinWriter) { t.NEP17Transfer.EncodeBinary(w) w.WriteVarBytes(t.ID) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (t *NEP11Transfer) DecodeBinary(r *io.BinReader) { t.NEP17Transfer.DecodeBinary(r) t.ID = r.ReadVarBytes(storage.MaxStorageKeyLen) diff --git a/pkg/core/transaction/attribute.go b/pkg/core/transaction/attribute.go index c81dbb1b5..91f8b66e5 100644 --- a/pkg/core/transaction/attribute.go +++ b/pkg/core/transaction/attribute.go @@ -26,7 +26,7 @@ type attrJSON struct { Type string `json:"type"` } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (attr *Attribute) DecodeBinary(br *io.BinReader) { attr.Type = AttrType(br.ReadB()) @@ -52,7 +52,7 @@ func (attr *Attribute) DecodeBinary(br *io.BinReader) { attr.Value.DecodeBinary(br) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (attr *Attribute) EncodeBinary(bw *io.BinWriter) { bw.WriteB(byte(attr.Type)) switch t := attr.Type; t { diff --git a/pkg/core/transaction/conflicts.go b/pkg/core/transaction/conflicts.go index daef11724..77eff8c64 100644 --- a/pkg/core/transaction/conflicts.go +++ b/pkg/core/transaction/conflicts.go @@ -10,7 +10,7 @@ type Conflicts struct { Hash util.Uint256 `json:"hash"` } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (c *Conflicts) DecodeBinary(br *io.BinReader) { bytes := br.ReadVarBytes(util.Uint256Size) if br.Err != nil { @@ -24,7 +24,7 @@ func (c *Conflicts) DecodeBinary(br *io.BinReader) { c.Hash = hash } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (c *Conflicts) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes(c.Hash.BytesBE()) } diff --git a/pkg/core/transaction/not_valid_before.go b/pkg/core/transaction/not_valid_before.go index aa64b14c0..46868dc2b 100644 --- a/pkg/core/transaction/not_valid_before.go +++ b/pkg/core/transaction/not_valid_before.go @@ -12,7 +12,7 @@ type NotValidBefore struct { Height uint32 `json:"height"` } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (n *NotValidBefore) DecodeBinary(br *io.BinReader) { bytes := br.ReadVarBytes(4) if br.Err != nil { @@ -25,7 +25,7 @@ func (n *NotValidBefore) DecodeBinary(br *io.BinReader) { n.Height = binary.LittleEndian.Uint32(bytes) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (n *NotValidBefore) EncodeBinary(w *io.BinWriter) { bytes := make([]byte, 4) binary.LittleEndian.PutUint32(bytes, n.Height) diff --git a/pkg/core/transaction/notary_assisted.go b/pkg/core/transaction/notary_assisted.go index bac00c3ba..436c4f42c 100644 --- a/pkg/core/transaction/notary_assisted.go +++ b/pkg/core/transaction/notary_assisted.go @@ -11,7 +11,7 @@ type NotaryAssisted struct { NKeys uint8 `json:"nkeys"` } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (n *NotaryAssisted) DecodeBinary(br *io.BinReader) { bytes := br.ReadVarBytes(1) if br.Err != nil { @@ -24,7 +24,7 @@ func (n *NotaryAssisted) DecodeBinary(br *io.BinReader) { n.NKeys = bytes[0] } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (n *NotaryAssisted) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes([]byte{n.NKeys}) } diff --git a/pkg/core/transaction/oracle.go b/pkg/core/transaction/oracle.go index 1442c80b3..2d396d2f7 100644 --- a/pkg/core/transaction/oracle.go +++ b/pkg/core/transaction/oracle.go @@ -51,12 +51,12 @@ func (c OracleResponseCode) IsValid() bool { c == InsufficientFunds || c == ContentTypeNotSupported || c == Error } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c OracleResponseCode) MarshalJSON() ([]byte, error) { return []byte(`"` + c.String() + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (c *OracleResponseCode) UnmarshalJSON(data []byte) error { var js string if err := json.Unmarshal(data, &js); err != nil { @@ -90,7 +90,7 @@ func (c *OracleResponseCode) UnmarshalJSON(data []byte) error { return nil } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (r *OracleResponse) DecodeBinary(br *io.BinReader) { r.ID = br.ReadU64LE() r.Code = OracleResponseCode(br.ReadB()) @@ -104,7 +104,7 @@ func (r *OracleResponse) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (r *OracleResponse) EncodeBinary(w *io.BinWriter) { w.WriteU64LE(r.ID) w.WriteB(byte(r.Code)) diff --git a/pkg/core/transaction/reserved.go b/pkg/core/transaction/reserved.go index 27acc36f2..cc622c708 100644 --- a/pkg/core/transaction/reserved.go +++ b/pkg/core/transaction/reserved.go @@ -9,12 +9,12 @@ type Reserved struct { Value []byte } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (e *Reserved) DecodeBinary(br *io.BinReader) { e.Value = br.ReadVarBytes() } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (e *Reserved) EncodeBinary(w *io.BinWriter) { w.WriteVarBytes(e.Value) } diff --git a/pkg/core/transaction/signer.go b/pkg/core/transaction/signer.go index d90e50598..5b42f56f5 100644 --- a/pkg/core/transaction/signer.go +++ b/pkg/core/transaction/signer.go @@ -20,7 +20,7 @@ type Signer struct { Rules []WitnessRule `json:"rules,omitempty"` } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (c *Signer) EncodeBinary(bw *io.BinWriter) { bw.WriteBytes(c.Account[:]) bw.WriteB(byte(c.Scopes)) @@ -35,7 +35,7 @@ func (c *Signer) EncodeBinary(bw *io.BinWriter) { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (c *Signer) DecodeBinary(br *io.BinReader) { br.ReadBytes(c.Account[:]) c.Scopes = WitnessScope(br.ReadB()) diff --git a/pkg/core/transaction/transaction.go b/pkg/core/transaction/transaction.go index af57f4e3f..e7af8e756 100644 --- a/pkg/core/transaction/transaction.go +++ b/pkg/core/transaction/transaction.go @@ -205,7 +205,7 @@ func (t *Transaction) decodeBinaryNoSize(br *io.BinReader, buf []byte) { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (t *Transaction) DecodeBinary(br *io.BinReader) { t.decodeBinaryNoSize(br, nil) @@ -214,7 +214,7 @@ func (t *Transaction) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (t *Transaction) EncodeBinary(bw *io.BinWriter) { t.encodeHashableFields(bw) bw.WriteVarUint(uint64(len(t.Scripts))) @@ -350,7 +350,7 @@ type transactionJSON struct { Scripts []Witness `json:"witnesses"` } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (t *Transaction) MarshalJSON() ([]byte, error) { tx := transactionJSON{ TxID: t.Hash(), @@ -369,7 +369,7 @@ func (t *Transaction) MarshalJSON() ([]byte, error) { return json.Marshal(tx) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (t *Transaction) UnmarshalJSON(data []byte) error { tx := new(transactionJSON) if err := json.Unmarshal(data, tx); err != nil { diff --git a/pkg/core/transaction/witness.go b/pkg/core/transaction/witness.go index 57f6d634a..dfa441b25 100644 --- a/pkg/core/transaction/witness.go +++ b/pkg/core/transaction/witness.go @@ -22,13 +22,13 @@ type Witness struct { VerificationScript []byte `json:"verification"` } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (w *Witness) DecodeBinary(br *io.BinReader) { w.InvocationScript = br.ReadVarBytes(MaxInvocationScript) w.VerificationScript = br.ReadVarBytes(MaxVerificationScript) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (w *Witness) EncodeBinary(bw *io.BinWriter) { bw.WriteVarBytes(w.InvocationScript) bw.WriteVarBytes(w.VerificationScript) diff --git a/pkg/core/transaction/witness_condition.go b/pkg/core/transaction/witness_condition.go index fb8e6ce39..316922605 100644 --- a/pkg/core/transaction/witness_condition.go +++ b/pkg/core/transaction/witness_condition.go @@ -100,30 +100,30 @@ type conditionAux struct { Type string `json:"type"` } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionBoolean) Type() WitnessConditionType { return WitnessBoolean } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionBoolean) Match(_ MatchContext) (bool, error) { return bool(*c), nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionBoolean) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) w.WriteBool(bool(*c)) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionBoolean) DecodeBinarySpecific(r *io.BinReader, maxDepth int) { *c = ConditionBoolean(r.ReadBool()) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionBoolean) MarshalJSON() ([]byte, error) { boolJSON, _ := json.Marshal(bool(*c)) // Simple boolean can't fail. aux := conditionAux{ @@ -139,31 +139,31 @@ func (c *ConditionBoolean) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), bool(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionNot) Type() WitnessConditionType { return WitnessNot } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionNot) Match(ctx MatchContext) (bool, error) { res, err := c.Condition.Match(ctx) return ((err == nil) && !res), err } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionNot) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) c.Condition.EncodeBinary(w) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionNot) DecodeBinarySpecific(r *io.BinReader, maxDepth int) { c.Condition = decodeBinaryCondition(r, maxDepth-1) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionNot) MarshalJSON() ([]byte, error) { condJSON, err := json.Marshal(c.Condition) if err != nil { @@ -176,18 +176,18 @@ func (c *ConditionNot) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionNot) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), c.Condition) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionAnd) Type() WitnessConditionType { return WitnessAnd } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionAnd) Match(ctx MatchContext) (bool, error) { for _, cond := range *c { @@ -202,7 +202,7 @@ func (c *ConditionAnd) Match(ctx MatchContext) (bool, error) { return true, nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionAnd) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) w.WriteArray([]WitnessCondition(*c)) @@ -228,7 +228,7 @@ func readArrayOfConditions(r *io.BinReader, maxDepth int) []WitnessCondition { return a } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionAnd) DecodeBinarySpecific(r *io.BinReader, maxDepth int) { a := readArrayOfConditions(r, maxDepth) @@ -253,23 +253,23 @@ func arrayToJSON(c WitnessCondition, a []WitnessCondition) ([]byte, error) { return json.Marshal(aux) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionAnd) MarshalJSON() ([]byte, error) { return arrayToJSON(c, []WitnessCondition(*c)) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionAnd) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), []WitnessCondition(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionOr) Type() WitnessConditionType { return WitnessOr } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionOr) Match(ctx MatchContext) (bool, error) { for _, cond := range *c { @@ -284,13 +284,13 @@ func (c *ConditionOr) Match(ctx MatchContext) (bool, error) { return false, nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionOr) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) w.WriteArray([]WitnessCondition(*c)) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionOr) DecodeBinarySpecific(r *io.BinReader, maxDepth int) { a := readArrayOfConditions(r, maxDepth) @@ -299,41 +299,41 @@ func (c *ConditionOr) DecodeBinarySpecific(r *io.BinReader, maxDepth int) { } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionOr) MarshalJSON() ([]byte, error) { return arrayToJSON(c, []WitnessCondition(*c)) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionOr) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), []WitnessCondition(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionScriptHash) Type() WitnessConditionType { return WitnessScriptHash } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionScriptHash) Match(ctx MatchContext) (bool, error) { return util.Uint160(*c).Equals(ctx.GetCurrentScriptHash()), nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionScriptHash) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) w.WriteBytes(c[:]) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionScriptHash) DecodeBinarySpecific(r *io.BinReader, _ int) { r.ReadBytes(c[:]) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionScriptHash) MarshalJSON() ([]byte, error) { aux := conditionAux{ Type: c.Type().String(), @@ -342,36 +342,36 @@ func (c *ConditionScriptHash) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionScriptHash) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), util.Uint160(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionGroup) Type() WitnessConditionType { return WitnessGroup } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionGroup) Match(ctx MatchContext) (bool, error) { return ctx.CurrentScriptHasGroup((*keys.PublicKey)(c)) } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionGroup) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) (*keys.PublicKey)(c).EncodeBinary(w) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionGroup) DecodeBinarySpecific(r *io.BinReader, _ int) { (*keys.PublicKey)(c).DecodeBinary(r) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionGroup) MarshalJSON() ([]byte, error) { aux := conditionAux{ Type: c.Type().String(), @@ -380,35 +380,35 @@ func (c *ConditionGroup) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionGroup) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), keys.PublicKey(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c ConditionCalledByEntry) Type() WitnessConditionType { return WitnessCalledByEntry } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c ConditionCalledByEntry) Match(ctx MatchContext) (bool, error) { entry := ctx.GetEntryScriptHash() return entry.Equals(ctx.GetCallingScriptHash()) || entry.Equals(ctx.GetCurrentScriptHash()), nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c ConditionCalledByEntry) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c ConditionCalledByEntry) DecodeBinarySpecific(_ *io.BinReader, _ int) { } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c ConditionCalledByEntry) MarshalJSON() ([]byte, error) { aux := conditionAux{ Type: c.Type().String(), @@ -416,36 +416,36 @@ func (c ConditionCalledByEntry) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c ConditionCalledByEntry) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), nil) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionCalledByContract) Type() WitnessConditionType { return WitnessCalledByContract } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionCalledByContract) Match(ctx MatchContext) (bool, error) { return util.Uint160(*c).Equals(ctx.GetCallingScriptHash()), nil } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionCalledByContract) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) w.WriteBytes(c[:]) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionCalledByContract) DecodeBinarySpecific(r *io.BinReader, _ int) { r.ReadBytes(c[:]) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionCalledByContract) MarshalJSON() ([]byte, error) { aux := conditionAux{ Type: c.Type().String(), @@ -454,36 +454,36 @@ func (c *ConditionCalledByContract) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// ToStackItem implements WitnessCondition interface allowing to convert +// ToStackItem implements the WitnessCondition interface allowing to convert // to stackitem.Item. func (c *ConditionCalledByContract) ToStackItem() stackitem.Item { return condToStackItem(c.Type(), util.Uint160(*c)) } -// Type implements WitnessCondition interface and returns condition type. +// Type implements the WitnessCondition interface and returns condition type. func (c *ConditionCalledByGroup) Type() WitnessConditionType { return WitnessCalledByGroup } -// Match implements WitnessCondition interface checking whether this condition +// Match implements the WitnessCondition interface checking whether this condition // matches given context. func (c *ConditionCalledByGroup) Match(ctx MatchContext) (bool, error) { return ctx.CallingScriptHasGroup((*keys.PublicKey)(c)) } -// EncodeBinary implements WitnessCondition interface allowing to serialize condition. +// EncodeBinary implements the WitnessCondition interface allowing to serialize condition. func (c *ConditionCalledByGroup) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(c.Type())) (*keys.PublicKey)(c).EncodeBinary(w) } -// DecodeBinarySpecific implements WitnessCondition interface allowing to +// DecodeBinarySpecific implements the WitnessCondition interface allowing to // deserialize condition-specific data. func (c *ConditionCalledByGroup) DecodeBinarySpecific(r *io.BinReader, _ int) { (*keys.PublicKey)(c).DecodeBinary(r) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c *ConditionCalledByGroup) MarshalJSON() ([]byte, error) { aux := conditionAux{ Type: c.Type().String(), diff --git a/pkg/core/transaction/witness_rule.go b/pkg/core/transaction/witness_rule.go index 15edeb699..05661f196 100644 --- a/pkg/core/transaction/witness_rule.go +++ b/pkg/core/transaction/witness_rule.go @@ -33,13 +33,13 @@ type witnessRuleAux struct { Condition json.RawMessage `json:"condition"` } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (w *WitnessRule) EncodeBinary(bw *io.BinWriter) { bw.WriteB(byte(w.Action)) w.Condition.EncodeBinary(bw) } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (w *WitnessRule) DecodeBinary(br *io.BinReader) { w.Action = WitnessAction(br.ReadB()) if br.Err == nil && w.Action != WitnessDeny && w.Action != WitnessAllow { @@ -49,7 +49,7 @@ func (w *WitnessRule) DecodeBinary(br *io.BinReader) { w.Condition = DecodeBinaryCondition(br) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (w *WitnessRule) MarshalJSON() ([]byte, error) { cond, err := w.Condition.MarshalJSON() if err != nil { @@ -62,7 +62,7 @@ func (w *WitnessRule) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (w *WitnessRule) UnmarshalJSON(data []byte) error { aux := &witnessRuleAux{} err := json.Unmarshal(data, aux) diff --git a/pkg/core/transaction/witness_scope.go b/pkg/core/transaction/witness_scope.go index 8950290cd..945fd3e92 100644 --- a/pkg/core/transaction/witness_scope.go +++ b/pkg/core/transaction/witness_scope.go @@ -88,12 +88,12 @@ func scopesToString(scopes WitnessScope) string { return res } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (s WitnessScope) MarshalJSON() ([]byte, error) { return []byte(`"` + scopesToString(s) + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (s *WitnessScope) UnmarshalJSON(data []byte) error { var js string if err := json.Unmarshal(data, &js); err != nil { diff --git a/pkg/crypto/hash/hash.go b/pkg/crypto/hash/hash.go index c56600c3c..9faa8b33d 100644 --- a/pkg/crypto/hash/hash.go +++ b/pkg/crypto/hash/hash.go @@ -8,7 +8,7 @@ import ( "golang.org/x/crypto/ripemd160" //nolint:staticcheck // SA1019: package golang.org/x/crypto/ripemd160 is deprecated ) -// Hashable represents an object which can be hashed. Usually these objects +// Hashable represents an object which can be hashed. Usually, these objects // are io.Serializable and signable. They tend to cache the hash inside for // effectiveness, providing this accessor method. Anything that can be // identified with a hash can then be signed and verified. @@ -24,7 +24,7 @@ func getSignedData(net uint32, hh Hashable) []byte { return b } -// NetSha256 calculates network-specific hash of Hashable item that can then +// NetSha256 calculates a network-specific hash of the Hashable item that can then // be signed/verified. func NetSha256(net uint32, hh Hashable) util.Uint256 { return Sha256(getSignedData(net, hh)) diff --git a/pkg/crypto/hash/merkle_tree.go b/pkg/crypto/hash/merkle_tree.go index 0893a4be2..09bca3eec 100644 --- a/pkg/crypto/hash/merkle_tree.go +++ b/pkg/crypto/hash/merkle_tree.go @@ -12,7 +12,7 @@ type MerkleTree struct { depth int } -// NewMerkleTree returns new MerkleTree object. +// NewMerkleTree returns a new MerkleTree object. func NewMerkleTree(hashes []util.Uint256) (*MerkleTree, error) { if len(hashes) == 0 { return nil, errors.New("length of the hashes cannot be zero") @@ -66,13 +66,11 @@ func buildMerkleTree(leaves []*MerkleTreeNode) *MerkleTreeNode { return buildMerkleTree(parents) } -// CalcMerkleRoot calculcates Merkle root hash value for a given slice of hashes. -// It doesn't create a full MerkleTree structure and it uses given slice as a +// CalcMerkleRoot calculates the Merkle root hash value for the given slice of hashes. +// It doesn't create a full MerkleTree structure and it uses the given slice as a // scratchpad, so it will destroy its contents in the process. But it's much more -// memory efficient if you only need root hash value, while NewMerkleTree would -// make 3*N allocations for N hashes, this function will only make 4. It also is -// an error to call this function for zero-length hashes slice, the function will -// panic. +// memory efficient if you only need a root hash value. While NewMerkleTree would +// make 3*N allocations for N hashes, this function will only make 4. func CalcMerkleRoot(hashes []util.Uint256) util.Uint256 { if len(hashes) == 0 { return util.Uint256{} diff --git a/pkg/crypto/keys/nep2.go b/pkg/crypto/keys/nep2.go index 547c6c7c0..abfa9277d 100644 --- a/pkg/crypto/keys/nep2.go +++ b/pkg/crypto/keys/nep2.go @@ -40,7 +40,7 @@ func NEP2ScryptParams() ScryptParams { } } -// NEP2Encrypt encrypts a the PrivateKey using a given passphrase +// NEP2Encrypt encrypts a the PrivateKey using the given passphrase // under the NEP-2 standard. func NEP2Encrypt(priv *PrivateKey, passphrase string, params ScryptParams) (s string, err error) { address := priv.Address() @@ -75,7 +75,7 @@ func NEP2Encrypt(priv *PrivateKey, passphrase string, params ScryptParams) (s st return base58.CheckEncode(buf.Bytes()), nil } -// NEP2Decrypt decrypts an encrypted key using a given passphrase +// NEP2Decrypt decrypts an encrypted key using the given passphrase // under the NEP-2 standard. func NEP2Decrypt(key, passphrase string, params ScryptParams) (*PrivateKey, error) { b, err := base58.CheckDecode(key) diff --git a/pkg/crypto/keys/private_key.go b/pkg/crypto/keys/private_key.go index 6cded1914..5e5992378 100644 --- a/pkg/crypto/keys/private_key.go +++ b/pkg/crypto/keys/private_key.go @@ -124,7 +124,7 @@ func (p *PrivateKey) Address() string { return pk.Address() } -// GetScriptHash returns verification script hash for public key associated with +// GetScriptHash returns verification script hash for the public key associated with // the private key. func (p *PrivateKey) GetScriptHash() util.Uint160 { pk := p.PublicKey() @@ -140,7 +140,7 @@ func (p *PrivateKey) Sign(data []byte) []byte { return p.SignHash(digest) } -// SignHash signs particular hash the private key. +// SignHash signs a particular hash with the private key. func (p *PrivateKey) SignHash(digest util.Uint256) []byte { r, s := rfc6979.SignECDSA(&p.PrivateKey, digest[:], sha256.New) return getSignatureSlice(p.PrivateKey.Curve, r, s) diff --git a/pkg/crypto/keys/publickey.go b/pkg/crypto/keys/publickey.go index b1e3748c2..49bfcc02f 100644 --- a/pkg/crypto/keys/publickey.go +++ b/pkg/crypto/keys/publickey.go @@ -22,7 +22,7 @@ import ( // coordLen is the number of bytes in serialized X or Y coordinate. const coordLen = 32 -// SignatureLen is the length of standard signature for 256-bit EC key. +// SignatureLen is the length of a standard signature for 256-bit EC key. const SignatureLen = 64 // PublicKeys is a list of public keys. @@ -68,7 +68,7 @@ func (keys *PublicKeys) Bytes() []byte { return buf.Bytes() } -// Contains checks whether passed param contained in PublicKeys. +// Contains checks whether the passed param is contained in PublicKeys. func (keys PublicKeys) Contains(pKey *PublicKey) bool { for _, key := range keys { if key.Equal(pKey) { @@ -78,14 +78,14 @@ func (keys PublicKeys) Contains(pKey *PublicKey) bool { return false } -// Copy returns copy of keys. +// Copy returns a copy of keys. func (keys PublicKeys) Copy() PublicKeys { res := make(PublicKeys, len(keys)) copy(res, keys) return res } -// Unique returns set of public keys. +// Unique returns a set of public keys. func (keys PublicKeys) Unique() PublicKeys { unique := PublicKeys{} for _, publicKey := range keys { @@ -133,7 +133,7 @@ func init() { keycache, _ = lru.New(1024) } -// NewPublicKeyFromBytes returns public key created from b using given EC. +// NewPublicKeyFromBytes returns a public key created from b using the given EC. func NewPublicKeyFromBytes(b []byte, curve elliptic.Curve) (*PublicKey, error) { var pubKey *PublicKey cachedKey, ok := keycache.Get(string(b)) @@ -194,12 +194,12 @@ func NewPublicKeyFromASN1(data []byte) (*PublicKey, error) { return &result, nil } -// decodeCompressedY performs decompression of Y coordinate for given X and Y's least significant bit. +// decodeCompressedY performs decompression of Y coordinate for the given X and Y's least significant bit. // We use here a short-form Weierstrass curve (https://www.hyperelliptic.org/EFD/g1p/auto-shortw.html) // y² = x³ + ax + b. Two types of elliptic curves are supported: // 1. Secp256k1 (Koblitz curve): y² = x³ + b, // 2. Secp256r1 (Random curve): y² = x³ - 3x + b. -// To decode compressed curve point we perform the following operation: y = sqrt(x³ + ax + b mod p) +// To decode a compressed curve point, we perform the following operation: y = sqrt(x³ + ax + b mod p) // where `p` denotes the order of the underlying curve field. func decodeCompressedY(x *big.Int, ylsb uint, curve elliptic.Curve) (*big.Int, error) { var a *big.Int @@ -371,7 +371,7 @@ func (p PublicKey) MarshalJSON() ([]byte, error) { return json.Marshal(hex.EncodeToString(p.Bytes())) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (p *PublicKey) UnmarshalJSON(data []byte) error { l := len(data) if l < 2 || data[0] != '"' || data[l-1] != '"' { diff --git a/pkg/crypto/keys/wif.go b/pkg/crypto/keys/wif.go index b8bf971bb..0e4d57b3d 100644 --- a/pkg/crypto/keys/wif.go +++ b/pkg/crypto/keys/wif.go @@ -23,7 +23,7 @@ type WIF struct { // A reference to the PrivateKey which this WIF is created from. PrivateKey *PrivateKey - // The string representation of the WIF. + // A string representation of the WIF. S string } diff --git a/pkg/crypto/verifiable.go b/pkg/crypto/verifiable.go index 68670ef16..5e992981b 100644 --- a/pkg/crypto/verifiable.go +++ b/pkg/crypto/verifiable.go @@ -3,7 +3,7 @@ package crypto import "github.com/nspcc-dev/neo-go/pkg/crypto/hash" // VerifiableDecodable represents an object which can be verified and -// those hashable part can be encoded/decoded. +// those hashable part of which can be encoded/decoded. type VerifiableDecodable interface { hash.Hashable EncodeHashableFields() ([]byte, error) diff --git a/pkg/encoding/address/address.go b/pkg/encoding/address/address.go index 3711beb78..f048d0f2f 100644 --- a/pkg/encoding/address/address.go +++ b/pkg/encoding/address/address.go @@ -8,9 +8,9 @@ import ( ) const ( - // NEO2Prefix is the first byte of address for NEO2. + // NEO2Prefix is the first byte of an address for NEO2. NEO2Prefix byte = 0x17 - // NEO3Prefix is the first byte of address for NEO3. + // NEO3Prefix is the first byte of an address for NEO3. NEO3Prefix byte = 0x35 ) @@ -20,13 +20,13 @@ var Prefix = NEO3Prefix // Uint160ToString returns the "NEO address" from the given Uint160. func Uint160ToString(u util.Uint160) string { - // Dont forget to prepend the Address version 0x17 (23) A + // Don't forget to prepend the Address version 0x17 (23) A b := append([]byte{Prefix}, u.BytesBE()...) return base58.CheckEncode(b) } // StringToUint160 attempts to decode the given NEO address string -// into an Uint160. +// into a Uint160. func StringToUint160(s string) (u util.Uint160, err error) { b, err := base58.CheckDecode(s) if err != nil { diff --git a/pkg/encoding/address/doc.go b/pkg/encoding/address/doc.go index 8ce8c7c9a..d5bd125a7 100644 --- a/pkg/encoding/address/doc.go +++ b/pkg/encoding/address/doc.go @@ -1,4 +1,4 @@ /* -Package address implements conversion of script hash to/from Neo address. +Package address implements conversion of a script hash to/from a Neo address. */ package address diff --git a/pkg/encoding/base58/base58.go b/pkg/encoding/base58/base58.go index 3598478ac..4abec466f 100644 --- a/pkg/encoding/base58/base58.go +++ b/pkg/encoding/base58/base58.go @@ -8,7 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/crypto/hash" ) -// CheckDecode implements a base58-encoded string decoding with hash-based +// CheckDecode implements base58-encoded string decoding with a hash-based // checksum check. func CheckDecode(s string) (b []byte, err error) { b, err = base58.Decode(s) @@ -30,7 +30,7 @@ func CheckDecode(s string) (b []byte, err error) { return b, nil } -// CheckEncode encodes given byte slice into a base58 string with hash-based +// CheckEncode encodes the given byte slice into a base58 string with a hash-based // checksum appended to it. func CheckEncode(b []byte) string { b = append(b, hash.Checksum(b)...) diff --git a/pkg/encoding/bigint/bigint.go b/pkg/encoding/bigint/bigint.go index a6b80b70a..41f3c599e 100644 --- a/pkg/encoding/bigint/bigint.go +++ b/pkg/encoding/bigint/bigint.go @@ -9,8 +9,8 @@ import ( ) const ( - // MaxBytesLen is the maximum length of serialized integer suitable for Neo VM. - MaxBytesLen = 33 // 32 bytes for 256-bit integer plus 1 if padding needed + // MaxBytesLen is the maximum length of a serialized integer suitable for Neo VM. + MaxBytesLen = 33 // 32 bytes for a 256-bit integer plus 1 if padding needed // wordSizeBytes is a size of a big.Word (uint) in bytes. wordSizeBytes = bits.UintSize / 8 ) @@ -78,7 +78,7 @@ func FromBytes(data []byte) *big.Int { return n.SetBits(ws) } -// getEffectiveSize returns minimal number of bytes required +// getEffectiveSize returns the minimal number of bytes required // to represent a number (two's complement for negatives). func getEffectiveSize(buf []byte, isNeg bool) int { var b byte @@ -96,7 +96,7 @@ func getEffectiveSize(buf []byte, isNeg bool) int { return size } -// ToBytes converts integer to a slice in little-endian format. +// ToBytes converts an integer to a slice in little-endian format. // Note: NEO3 serialization differs from default C# BigInteger.ToByteArray() // when n == 0. For zero is equal to empty slice in NEO3. // https://github.com/neo-project/neo-vm/blob/master/src/neo-vm/Types/Integer.cs#L16 @@ -104,7 +104,7 @@ func ToBytes(n *big.Int) []byte { return ToPreallocatedBytes(n, []byte{}) } -// ToPreallocatedBytes converts integer to a slice in little-endian format using given +// ToPreallocatedBytes converts an integer to a slice in little-endian format using the given // byte array for conversion result. func ToPreallocatedBytes(n *big.Int, data []byte) []byte { sign := n.Sign() diff --git a/pkg/encoding/fixedn/decimal.go b/pkg/encoding/fixedn/decimal.go index f26976e47..4a6cfc8e0 100644 --- a/pkg/encoding/fixedn/decimal.go +++ b/pkg/encoding/fixedn/decimal.go @@ -36,7 +36,7 @@ func pow10(n int) *big.Int { return p } -// ToString converts big decimal with specified precision to string. +// ToString converts a big decimal with the specified precision to a string. func ToString(bi *big.Int, precision int) string { var dp, fp big.Int dp.QuoRem(bi, pow10(precision), &fp) @@ -53,7 +53,7 @@ func ToString(bi *big.Int, precision int) string { return s + "." + fmt.Sprintf("%0"+strconv.FormatUint(uint64(precision-trimmed), 10)+"d", frac) } -// FromString converts string to a big decimal with specified precision. +// FromString converts a string to a big decimal with the specified precision. func FromString(s string, precision int) (*big.Int, error) { parts := strings.SplitN(s, ".", 2) bi, ok := new(big.Int).SetString(parts[0], 10) diff --git a/pkg/encoding/fixedn/fixed8.go b/pkg/encoding/fixedn/fixed8.go index af3b82f9c..3bea85b3a 100644 --- a/pkg/encoding/fixedn/fixed8.go +++ b/pkg/encoding/fixedn/fixed8.go @@ -42,13 +42,13 @@ func (f Fixed8) FloatValue() float64 { return float64(f) / decimals } -// IntegralValue returns integer part of the original value representing +// IntegralValue returns an integer part of the original value representing // Fixed8 as int64. func (f Fixed8) IntegralValue() int64 { return int64(f) / decimals } -// FractionalValue returns decimal part of the original value. It has the same +// FractionalValue returns a decimal part of the original value. It has the same // sign as f, so that f = f.IntegralValue() + f.FractionalValue(). func (f Fixed8) FractionalValue() int32 { return int32(int64(f) % decimals) diff --git a/pkg/interop/contract/contract.go b/pkg/interop/contract/contract.go index 88f4295e3..2f3843ee3 100644 --- a/pkg/interop/contract/contract.go +++ b/pkg/interop/contract/contract.go @@ -24,27 +24,27 @@ const ( NoneFlag CallFlag = 0 ) -// CreateMultisigAccount calculates script hash of an m out of n multisignature -// script using given m and a set of public keys bytes. This function uses +// CreateMultisigAccount calculates a script hash of an m out of n multisignature +// script using the given m and a set of public keys bytes. This function uses // `System.Contract.CreateMultisigAccount` syscall. func CreateMultisigAccount(m int, pubs []interop.PublicKey) []byte { return neogointernal.Syscall2("System.Contract.CreateMultisigAccount", m, pubs).([]byte) } -// CreateStandardAccount calculates script hash of a given public key. +// CreateStandardAccount calculates a script hash of the given public key. // This function uses `System.Contract.CreateStandardAccount` syscall. func CreateStandardAccount(pub interop.PublicKey) []byte { return neogointernal.Syscall1("System.Contract.CreateStandardAccount", pub).([]byte) } -// GetCallFlags returns calling flags which execution context was created with. +// GetCallFlags returns the calling flags which execution context was created with. // This function uses `System.Contract.GetCallFlags` syscall. func GetCallFlags() CallFlag { return neogointernal.Syscall0("System.Contract.GetCallFlags").(CallFlag) } -// Call executes previously deployed blockchain contract with specified hash -// (20 bytes in BE form) using provided arguments and call flags. +// Call executes the previously deployed blockchain contract with the specified hash +// (20 bytes in BE form) using the provided arguments and call flags. // It returns whatever this contract returns. This function uses // `System.Contract.Call` syscall. func Call(scriptHash interop.Hash160, method string, f CallFlag, args ...interface{}) interface{} { diff --git a/pkg/interop/crypto/crypto.go b/pkg/interop/crypto/crypto.go index 3b0fb1fd5..2d7e70934 100644 --- a/pkg/interop/crypto/crypto.go +++ b/pkg/interop/crypto/crypto.go @@ -8,14 +8,14 @@ import ( "github.com/nspcc-dev/neo-go/pkg/interop/neogointernal" ) -// CheckMultisig checks that script container (transaction) is signed by multiple +// CheckMultisig checks that the script container (transaction) is signed by multiple // ECDSA keys at once. It uses `System.Crypto.CheckMultisig` syscall. func CheckMultisig(pubs []interop.PublicKey, sigs []interop.Signature) bool { return neogointernal.Syscall2("System.Crypto.CheckMultisig", pubs, sigs).(bool) } -// CheckSig checks that sig is correct signature of the script container -// (transaction) for a given pub (serialized public key). It uses +// CheckSig checks that sig is a correct signature of the script container +// (transaction) for the given pub (serialized public key). It uses // `System.Crypto.CheckSig` syscall. func CheckSig(pub interop.PublicKey, sig interop.Signature) bool { return neogointernal.Syscall2("System.Crypto.CheckSig", pub, sig).(bool) diff --git a/pkg/interop/iterator/iterator.go b/pkg/interop/iterator/iterator.go index 778bc33f7..c24ae6ffe 100644 --- a/pkg/interop/iterator/iterator.go +++ b/pkg/interop/iterator/iterator.go @@ -20,10 +20,10 @@ func Next(it Iterator) bool { } // Value returns iterator's current value. It's only valid to call after -// successful Next call. This function uses `System.Iterator.Value` syscall. -// For slices the result is just value. -// For maps the result can be casted to a slice of 2 elements: key and value. -// For storage iterators refer to `storage.FindFlags` documentation. +// a successful Next call. This function uses `System.Iterator.Value` syscall. +// For slices, the result is just value. +// For maps, the result can be casted to a slice of 2 elements: a key and a value. +// For storage iterators, refer to `storage.FindFlags` documentation. func Value(it Iterator) interface{} { return neogointernal.Syscall1("System.Iterator.Value", it) } diff --git a/pkg/interop/math/math.go b/pkg/interop/math/math.go index 851e318a4..796a73e57 100644 --- a/pkg/interop/math/math.go +++ b/pkg/interop/math/math.go @@ -11,7 +11,7 @@ func Pow(a, b int) int { return neogointernal.Opcode2("POW", a, b).(int) } -// Sqrt returns positive square root of x rounded down. +// Sqrt returns a positive square root of x rounded down. func Sqrt(x int) int { return neogointernal.Opcode1("SQRT", x).(int) } @@ -25,17 +25,17 @@ func Sign(a int) int { return neogointernal.Opcode1("SIGN", a).(int) } -// Abs returns absolute value of a. +// Abs returns an absolute value of a. func Abs(a int) int { return neogointernal.Opcode1("ABS", a).(int) } -// Max returns maximum of a, b. +// Max returns the maximum of a, b. func Max(a, b int) int { return neogointernal.Opcode2("MAX", a, b).(int) } -// Min returns minimum of a, b. +// Min returns the minimum of a, b. func Min(a, b int) int { return neogointernal.Opcode2("MIN", a, b).(int) } diff --git a/pkg/interop/native/crypto/crypto.go b/pkg/interop/native/crypto/crypto.go index 8374cc26d..8055a6b07 100644 --- a/pkg/interop/native/crypto/crypto.go +++ b/pkg/interop/native/crypto/crypto.go @@ -13,7 +13,7 @@ import ( // Hash represents CryptoLib contract hash. const Hash = "\x1b\xf5\x75\xab\x11\x89\x68\x84\x13\x61\x0a\x35\xa1\x28\x86\xcd\xe0\xb6\x6c\x72" -// NamedCurve represents named elliptic curve. +// NamedCurve represents a named elliptic curve. type NamedCurve byte // Various named elliptic curves. @@ -39,7 +39,7 @@ func Murmur32(b []byte, seed int) []byte { } // VerifyWithECDsa calls `verifyWithECDsa` method of native CryptoLib contract and checks that sig is -// correct msg's signature for a given pub (serialized public key on a given curve). +// a correct msg's signature for the given pub (serialized public key on the given curve). func VerifyWithECDsa(msg []byte, pub interop.PublicKey, sig interop.Signature, curve NamedCurve) bool { return neogointernal.CallWithToken(Hash, "verifyWithECDsa", int(contract.NoneFlag), msg, pub, sig, curve).(bool) } diff --git a/pkg/interop/native/ledger/block.go b/pkg/interop/native/ledger/block.go index dfd7f0c84..01fbe1087 100644 --- a/pkg/interop/native/ledger/block.go +++ b/pkg/interop/native/ledger/block.go @@ -2,9 +2,9 @@ package ledger import "github.com/nspcc-dev/neo-go/pkg/interop" -// Block represents a NEO block, it's a data structure that you can get +// Block represents a NEO block, it's a data structure where you can get // block-related data from. It's similar to the Block class in the Neo .net -// framework. To use it you need to get it via GetBlock function call. +// framework. To use it, you need to get it via GetBlock function call. type Block struct { // Hash represents the hash (256 bit BE value in a 32 byte slice) of the // given block. @@ -23,7 +23,7 @@ type Block struct { Nonce int // Index represents the height of the block. Index int - // NextConsensus represents contract address of the next miner (160 bit BE + // NextConsensus represents the contract address of the next miner (160 bit BE // value in a 20 byte slice). NextConsensus interop.Hash160 // TransactionsLength represents the length of block's transactions array. diff --git a/pkg/interop/native/ledger/ledger.go b/pkg/interop/native/ledger/ledger.go index d0e3956f1..f26a15fa4 100644 --- a/pkg/interop/native/ledger/ledger.go +++ b/pkg/interop/native/ledger/ledger.go @@ -1,5 +1,5 @@ /* -Package ledger provides interface to LedgerContract native contract. +Package ledger provides an interface to LedgerContract native contract. It allows to access ledger contents like transactions and blocks. */ package ledger diff --git a/pkg/interop/native/ledger/transaction.go b/pkg/interop/native/ledger/transaction.go index 0cc7c49d2..9b162ad28 100644 --- a/pkg/interop/native/ledger/transaction.go +++ b/pkg/interop/native/ledger/transaction.go @@ -15,13 +15,13 @@ type Transaction struct { // Sender represents the sender (160 bit BE value in a 20 byte slice) of the // given Transaction. Sender interop.Hash160 - // SysFee represents fee to be burned. + // SysFee represents the fee to be burned. SysFee int - // NetFee represents fee to be distributed to consensus nodes. + // NetFee represents the fee to be distributed to consensus nodes. NetFee int // ValidUntilBlock is the maximum blockchain height exceeding which - // transaction should fail verification. + // a transaction should fail verification. ValidUntilBlock int - // Script represents code to run in NeoVM for this transaction. + // Script represents a code to run in NeoVM for this transaction. Script []byte } diff --git a/pkg/interop/native/management/contract.go b/pkg/interop/native/management/contract.go index e8021c31c..31778e2e4 100644 --- a/pkg/interop/native/management/contract.go +++ b/pkg/interop/native/management/contract.go @@ -2,7 +2,7 @@ package management import "github.com/nspcc-dev/neo-go/pkg/interop" -// Contract represents deployed contract. +// Contract represents a deployed contract. type Contract struct { ID int UpdateCounter int @@ -49,7 +49,7 @@ type ABI struct { Events []Event } -// Method represents contract method. +// Method represents a contract method. type Method struct { Name string Params []Parameter @@ -58,13 +58,13 @@ type Method struct { Safe bool } -// Event represents contract event. +// Event represents a contract event. type Event struct { Name string Params []Parameter } -// Parameter represents method parameter. +// Parameter represents a method parameter. type Parameter struct { Name string Type ParameterType @@ -76,7 +76,7 @@ type Permission struct { Methods []string } -// Group represents manifest group. +// Group represents a manifest group. type Group struct { PublicKey interop.PublicKey Signature interop.Signature diff --git a/pkg/interop/native/management/management.go b/pkg/interop/native/management/management.go index ff967c77b..0f3fbe20f 100644 --- a/pkg/interop/native/management/management.go +++ b/pkg/interop/native/management/management.go @@ -1,5 +1,5 @@ /* -Package management provides interface to ContractManagement native contract. +Package management provides an interface to ContractManagement native contract. It allows to get/deploy/update contracts as well as get/set deployment fee. */ package management diff --git a/pkg/interop/native/neo/neo.go b/pkg/interop/native/neo/neo.go index 4295c9a8b..fbed674c3 100644 --- a/pkg/interop/native/neo/neo.go +++ b/pkg/interop/native/neo/neo.go @@ -1,5 +1,5 @@ /* -Package neo provides interface to NeoToken native contract. +Package neo provides an interface to NeoToken native contract. NEO token is special, it's not just a regular NEP-17 contract, it also provides access to chain-specific settings and implements committee voting system. @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/interop/neogointernal" ) -// AccountState contains info about NEO holder. +// AccountState contains info about a NEO holder. type AccountState struct { Balance int Height int diff --git a/pkg/interop/native/notary/notary.go b/pkg/interop/native/notary/notary.go index cacfc0acf..d5668ed66 100644 --- a/pkg/interop/native/notary/notary.go +++ b/pkg/interop/native/notary/notary.go @@ -1,7 +1,7 @@ /* -Package notary provides interface to Notary native contract. +Package notary provides an interface to Notary native contract. This contract is a NeoGo extension and is not available on regular Neo -networks. To use it you need to have this extension enabled on the network. +networks. To use it, you need to have this extension enabled on the network. */ package notary diff --git a/pkg/interop/native/oracle/oracle.go b/pkg/interop/native/oracle/oracle.go index 036a4a7e9..48e5b184f 100644 --- a/pkg/interop/native/oracle/oracle.go +++ b/pkg/interop/native/oracle/oracle.go @@ -1,5 +1,5 @@ /* -Package oracle provides interface to OracleContract native contract. +Package oracle provides an interface to OracleContract native contract. Oracles allow you to get external (non-blockchain) data using HTTPS or NeoFS protocols. */ @@ -28,12 +28,12 @@ const ( // Hash represents Oracle contract hash. const Hash = "\x58\x87\x17\x11\x7e\x0a\xa8\x10\x72\xaf\xab\x71\xd2\xdd\x89\xfe\x7c\x4b\x92\xfe" -// MinimumResponseGas is the minimum response fee permitted for request (that is +// MinimumResponseGas is the minimum response fee permitted for a request (that is // you can't attach less than that to your request). It's 0.1 GAS at the moment. const MinimumResponseGas = 10_000_000 // Request makes an oracle request. It can only be successfully invoked by -// deployed contract and it takes the following parameters: +// a deployed contract and it takes the following parameters: // // url // URL to fetch, only https and neofs URLs are supported like @@ -41,7 +41,7 @@ const MinimumResponseGas = 10_000_000 // neofs:6pJtLUnGqDxE2EitZYLsDzsfTDVegD6BrRUn8QAFZWyt/5Cyxb3wrHDw5pqY63hb5otCSsJ24ZfYmsA8NAjtho2gr // // filter -// JSONPath filter to process the result, if specified it will be +// JSONPath filter to process the result; if specified, it will be // applied to the data returned from HTTP/NeoFS and you'll only get // filtered data in your callback method. // @@ -54,7 +54,7 @@ const MinimumResponseGas = 10_000_000 // // where url is the same url specified for Request, userData is anything // passed in the next parameter, code is the status of the reply and -// result is data returned from request if any. +// result is the data returned from the request if any. // // userData // data to pass to the callback function. @@ -71,12 +71,12 @@ func Request(url string, filter []byte, cb string, userData interface{}, gasForR url, filter, cb, userData, gasForResponse) } -// GetPrice returns current oracle request price. +// GetPrice returns the current oracle request price. func GetPrice() int { return neogointernal.CallWithToken(Hash, "getPrice", int(contract.ReadStates)).(int) } -// SetPrice allows to set oracle request price. This method can only be +// SetPrice allows to set the oracle request price. This method can only be // successfully invoked by the committee. func SetPrice(amount int) { neogointernal.CallWithTokenNoRet(Hash, "setPrice", int(contract.States), amount) diff --git a/pkg/interop/native/policy/policy.go b/pkg/interop/native/policy/policy.go index 58eb45f72..b7aeeaca1 100644 --- a/pkg/interop/native/policy/policy.go +++ b/pkg/interop/native/policy/policy.go @@ -1,5 +1,5 @@ /* -Package policy provides interface to PolicyContract native contract. +Package policy provides an interface to PolicyContract native contract. This contract holds various network-wide settings. */ package policy diff --git a/pkg/interop/native/roles/roles.go b/pkg/interop/native/roles/roles.go index da4134f3b..e0727c4f7 100644 --- a/pkg/interop/native/roles/roles.go +++ b/pkg/interop/native/roles/roles.go @@ -1,5 +1,5 @@ /* -Package roles provides interface to RoleManagement native contract. +Package roles provides an interface to RoleManagement native contract. Role management contract is used by committee to designate some nodes as providing some service on the network. */ @@ -14,7 +14,7 @@ import ( // Hash represents RoleManagement contract hash. const Hash = "\xe2\x95\xe3\x91\x54\x4c\x17\x8a\xd9\x4f\x03\xec\x4d\xcd\xff\x78\x53\x4e\xcf\x49" -// Role represents node role. +// Role represents a node role. type Role byte // Various node roles. diff --git a/pkg/interop/native/std/std.go b/pkg/interop/native/std/std.go index 274f34d9f..7d65ec617 100644 --- a/pkg/interop/native/std/std.go +++ b/pkg/interop/native/std/std.go @@ -1,5 +1,5 @@ /* -Package std provides interface to StdLib native contract. +Package std provides an interface to StdLib native contract. It implements various useful conversion functions. */ package std @@ -14,7 +14,7 @@ const Hash = "\xc0\xef\x39\xce\xe0\xe4\xe9\x25\xc6\xc2\xa0\x6a\x79\xe1\x44\x0d\x // Serialize calls `serialize` method of StdLib native contract and serializes // any given item into a byte slice. It works for all regular VM types (not ones -// from interop package) and allows to save them in storage or pass into Notify +// from interop package) and allows to save them in the storage or pass them into Notify // and then Deserialize them on the next run or in the external event receiver. func Serialize(item interface{}) []byte { return neogointernal.CallWithToken(Hash, "serialize", int(contract.NoneFlag), @@ -22,13 +22,13 @@ func Serialize(item interface{}) []byte { } // Deserialize calls `deserialize` method of StdLib native contract and unpacks -// previously serialized value from a byte slice, it's the opposite of Serialize. +// a previously serialized value from a byte slice, it's the opposite of Serialize. func Deserialize(b []byte) interface{} { return neogointernal.CallWithToken(Hash, "deserialize", int(contract.NoneFlag), b) } -// JSONSerialize serializes value to json. It uses `jsonSerialize` method of StdLib native +// JSONSerialize serializes a value to json. It uses `jsonSerialize` method of StdLib native // contract. // Serialization format is the following: // []byte -> base64 string @@ -43,7 +43,7 @@ func JSONSerialize(item interface{}) []byte { item).([]byte) } -// JSONDeserialize deserializes value from json. It uses `jsonDeserialize` method of StdLib +// JSONDeserialize deserializes a value from json. It uses `jsonDeserialize` method of StdLib // native contract. // It performs deserialization as follows: // strings -> []byte (string) from base64 @@ -57,7 +57,7 @@ func JSONDeserialize(data []byte) interface{} { } // Base64Encode calls `base64Encode` method of StdLib native contract and encodes -// given byte slice into a base64 string and returns byte representation of this +// the given byte slice into a base64 string and returns byte representation of this // string. func Base64Encode(b []byte) string { return neogointernal.CallWithToken(Hash, "base64Encode", int(contract.NoneFlag), @@ -65,14 +65,14 @@ func Base64Encode(b []byte) string { } // Base64Decode calls `base64Decode` method of StdLib native contract and decodes -// given base64 string represented as a byte slice into byte slice. +// the given base64 string represented as a byte slice into byte slice. func Base64Decode(b []byte) []byte { return neogointernal.CallWithToken(Hash, "base64Decode", int(contract.NoneFlag), b).([]byte) } // Base58Encode calls `base58Encode` method of StdLib native contract and encodes -// given byte slice into a base58 string and returns byte representation of this +// the given byte slice into a base58 string and returns byte representation of this // string. func Base58Encode(b []byte) string { return neogointernal.CallWithToken(Hash, "base58Encode", int(contract.NoneFlag), @@ -80,14 +80,14 @@ func Base58Encode(b []byte) string { } // Base58Decode calls `base58Decode` method of StdLib native contract and decodes -// given base58 string represented as a byte slice into a new byte slice. +// the given base58 string represented as a byte slice into a new byte slice. func Base58Decode(b []byte) []byte { return neogointernal.CallWithToken(Hash, "base58Decode", int(contract.NoneFlag), b).([]byte) } // Base58CheckEncode calls `base58CheckEncode` method of StdLib native contract and encodes -// given byte slice into a base58 string with checksum and returns byte representation of this +// the given byte slice into a base58 string with checksum and returns byte representation of this // string. func Base58CheckEncode(b []byte) string { return neogointernal.CallWithToken(Hash, "base58CheckEncode", int(contract.NoneFlag), @@ -95,34 +95,34 @@ func Base58CheckEncode(b []byte) string { } // Base58CheckDecode calls `base58CheckDecode` method of StdLib native contract and decodes -// given base58 string with a checksum represented as a byte slice into a new byte slice. +// thr given base58 string with a checksum represented as a byte slice into a new byte slice. func Base58CheckDecode(b []byte) []byte { return neogointernal.CallWithToken(Hash, "base58CheckDecode", int(contract.NoneFlag), b).([]byte) } -// Itoa converts num in a given base to string. Base should be either 10 or 16. +// Itoa converts num in the given base to a string. Base should be either 10 or 16. // It uses `itoa` method of StdLib native contract. func Itoa(num int, base int) string { return neogointernal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), num, base).(string) } -// Itoa10 converts num in a base 10 to string. +// Itoa10 converts num in base 10 to a string. // It uses `itoa` method of StdLib native contract. func Itoa10(num int) string { return neogointernal.CallWithToken(Hash, "itoa", int(contract.NoneFlag), num).(string) } -// Atoi converts string to a number in a given base. Base should be either 10 or 16. +// Atoi converts a string to a number in the given base. Base should be either 10 or 16. // It uses `atoi` method of StdLib native contract. func Atoi(s string, base int) int { return neogointernal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), s, base).(int) } -// Atoi10 converts string to a number in a base 10. +// Atoi10 converts a string to a number in base 10. // It uses `atoi` method of StdLib native contract. func Atoi10(s string) int { return neogointernal.CallWithToken(Hash, "atoi", int(contract.NoneFlag), @@ -137,35 +137,35 @@ func MemoryCompare(s1, s2 []byte) int { s1, s2).(int) } -// MemorySearch returns index of the first occurrence of val in mem. +// MemorySearch returns the index of the first occurrence of the val in the mem. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearch(mem, pattern []byte) int { return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern).(int) } -// MemorySearchIndex returns index of the first occurrence of val in mem starting from start. +// MemorySearchIndex returns the index of the first occurrence of the val in the mem starting from the start. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearchIndex(mem, pattern []byte, start int) int { return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern, start).(int) } -// MemorySearchLastIndex returns index of the last occurrence of val in mem ending before start. +// MemorySearchLastIndex returns the index of the last occurrence of the val in the mem ending before start. // If not found, -1 is returned. It uses `memorySearch` method of StdLib native contract. func MemorySearchLastIndex(mem, pattern []byte, start int) int { return neogointernal.CallWithToken(Hash, "memorySearch", int(contract.NoneFlag), mem, pattern, start, true).(int) } -// StringSplit splits s by occurrences of sep. +// StringSplit splits s by occurrences of the sep. // It uses `stringSplit` method of StdLib native contract. func StringSplit(s, sep string) []string { return neogointernal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), s, sep).([]string) } -// StringSplitNonEmpty splits s by occurrences of sep and returns a list of non-empty items. +// StringSplitNonEmpty splits s by occurrences of the sep and returns a list of non-empty items. // It uses `stringSplit` method of StdLib native contract. func StringSplitNonEmpty(s, sep string) []string { return neogointernal.CallWithToken(Hash, "stringSplit", int(contract.NoneFlag), diff --git a/pkg/io/binaryBufWriter.go b/pkg/io/binaryBufWriter.go index e64b58f2c..2b4dd8973 100644 --- a/pkg/io/binaryBufWriter.go +++ b/pkg/io/binaryBufWriter.go @@ -5,11 +5,11 @@ import ( "errors" ) -// ErrDrained is returned on an attempt to use already drained write buffer. +// ErrDrained is returned on an attempt to use an already drained write buffer. var ErrDrained = errors.New("buffer already drained") // BufBinWriter is an additional layer on top of BinWriter that -// automatically creates buffer to write into that you can get after all +// automatically creates a buffer to write into that you can get after all // writes via Bytes(). type BufBinWriter struct { *BinWriter @@ -28,7 +28,7 @@ func (bw *BufBinWriter) Len() int { return bw.buf.Len() } -// Bytes returns resulting buffer and makes future writes return an error. +// Bytes returns the resulting buffer and makes future writes return an error. func (bw *BufBinWriter) Bytes() []byte { if bw.Err != nil { return nil @@ -38,8 +38,8 @@ func (bw *BufBinWriter) Bytes() []byte { } // Reset resets the state of the buffer, making it usable again. It can -// make buffer usage somewhat more efficient, because you don't need to -// create it again, but beware that the buffer is gonna be the same as the one +// make buffer usage somewhat more efficient because you don't need to +// create it again. But beware, the buffer is gonna be the same as the one // returned by Bytes(), so if you need that data after Reset() you have to copy // it yourself. func (bw *BufBinWriter) Reset() { diff --git a/pkg/io/binaryReader.go b/pkg/io/binaryReader.go index e31921400..34abd7976 100644 --- a/pkg/io/binaryReader.go +++ b/pkg/io/binaryReader.go @@ -12,7 +12,7 @@ import ( // It is taken from https://github.com/neo-project/neo/blob/master/neo/IO/Helper.cs#L130 const MaxArraySize = 0x1000000 -// BinReader is a convenient wrapper around a io.Reader and err object. +// BinReader is a convenient wrapper around an io.Reader and err object. // Used to simplify error handling when reading into a struct with many fields. type BinReader struct { r io.Reader @@ -25,7 +25,7 @@ func NewBinReaderFromIO(ior io.Reader) *BinReader { return &BinReader{r: ior} } -// NewBinReaderFromBuf makes a BinReader from byte buffer. +// NewBinReaderFromBuf makes a BinReader from a byte buffer. func NewBinReaderFromBuf(b []byte) *BinReader { r := bytes.NewReader(b) return NewBinReaderFromIO(r) @@ -98,7 +98,7 @@ func (r *BinReader) ReadBool() bool { return r.ReadB() != 0 } -// ReadArray reads array into value which must be +// ReadArray reads an array into a value which must be // a pointer to a slice. func (r *BinReader) ReadArray(t interface{}, maxSize ...int) { value := reflect.ValueOf(t) @@ -187,7 +187,7 @@ func (r *BinReader) ReadVarBytes(maxSize ...int) []byte { return b } -// ReadBytes copies fixed-size buffer from the reader to provided slice. +// ReadBytes copies a fixed-size buffer from the reader to the provided slice. func (r *BinReader) ReadBytes(buf []byte) { if r.Err != nil { return diff --git a/pkg/io/binaryWriter.go b/pkg/io/binaryWriter.go index dc563b149..6188a70d8 100644 --- a/pkg/io/binaryWriter.go +++ b/pkg/io/binaryWriter.go @@ -7,8 +7,8 @@ import ( "reflect" ) -// BinWriter is a convenient wrapper around a io.Writer and err object. -// Used to simplify error handling when writing into a io.Writer +// BinWriter is a convenient wrapper around an io.Writer and err object. +// Used to simplify error handling when writing into an io.Writer // from a struct with many fields. type BinWriter struct { w io.Writer @@ -21,28 +21,28 @@ func NewBinWriterFromIO(iow io.Writer) *BinWriter { return &BinWriter{w: iow} } -// WriteU64LE writes an uint64 value into the underlying io.Writer in +// WriteU64LE writes a uint64 value into the underlying io.Writer in // little-endian format. func (w *BinWriter) WriteU64LE(u64 uint64) { binary.LittleEndian.PutUint64(w.uv[:8], u64) w.WriteBytes(w.uv[:8]) } -// WriteU32LE writes an uint32 value into the underlying io.Writer in +// WriteU32LE writes a uint32 value into the underlying io.Writer in // little-endian format. func (w *BinWriter) WriteU32LE(u32 uint32) { binary.LittleEndian.PutUint32(w.uv[:4], u32) w.WriteBytes(w.uv[:4]) } -// WriteU16LE writes an uint16 value into the underlying io.Writer in +// WriteU16LE writes a uint16 value into the underlying io.Writer in // little-endian format. func (w *BinWriter) WriteU16LE(u16 uint16) { binary.LittleEndian.PutUint16(w.uv[:2], u16) w.WriteBytes(w.uv[:2]) } -// WriteU16BE writes an uint16 value into the underlying io.Writer in +// WriteU16BE writes a uint16 value into the underlying io.Writer in // big-endian format. func (w *BinWriter) WriteU16BE(u16 uint16) { binary.BigEndian.PutUint16(w.uv[:2], u16) @@ -66,7 +66,7 @@ func (w *BinWriter) WriteBool(b bool) { } // WriteArray writes a slice or an array arr into w. Note that nil slices and -// empty slices are gonna be treated the same resulting in equal zero-length +// empty slices are gonna be treated the same resulting in an equal zero-length // array encoded. func (w *BinWriter) WriteArray(arr interface{}) { switch val := reflect.ValueOf(arr); val.Kind() { @@ -104,7 +104,7 @@ func (w *BinWriter) WriteVarUint(val uint64) { w.WriteBytes(w.uv[:n]) } -// PutVarUint puts val in varint form to the pre-allocated buffer. +// PutVarUint puts a val in the varint form to the pre-allocated buffer. func PutVarUint(data []byte, val uint64) int { _ = data[8] if val < 0xfd { @@ -150,7 +150,7 @@ func (w *BinWriter) WriteString(s string) { _, w.Err = io.WriteString(w.w, s) } -// Grow tries to increase underlying buffer capacity so that at least n bytes +// Grow tries to increase the underlying buffer capacity so that at least n bytes // can be written without reallocation. If the writer is not a buffer, this is a no-op. func (w *BinWriter) Grow(n int) { if b, ok := w.w.(*bytes.Buffer); ok { diff --git a/pkg/io/binaryrw_test.go b/pkg/io/binaryrw_test.go index fd998d503..40bfdb097 100644 --- a/pkg/io/binaryrw_test.go +++ b/pkg/io/binaryrw_test.go @@ -326,24 +326,24 @@ func TestWriteBytes(t *testing.T) { type testSerializable uint16 -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (t testSerializable) EncodeBinary(w *BinWriter) { w.WriteU16LE(uint16(t)) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (t *testSerializable) DecodeBinary(r *BinReader) { *t = testSerializable(r.ReadU16LE()) } type testPtrSerializable uint16 -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (t *testPtrSerializable) EncodeBinary(w *BinWriter) { w.WriteU16LE(uint16(*t)) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (t *testPtrSerializable) DecodeBinary(r *BinReader) { *t = testPtrSerializable(r.ReadU16LE()) } diff --git a/pkg/io/fileWriter.go b/pkg/io/fileWriter.go index 5e367b3eb..7ddf500e2 100644 --- a/pkg/io/fileWriter.go +++ b/pkg/io/fileWriter.go @@ -6,7 +6,7 @@ import ( "path/filepath" ) -// MakeDirForFile creates directory provided in filePath. +// MakeDirForFile creates a directory provided in the filePath. func MakeDirForFile(filePath string, creator string) error { fileName := filePath dir := filepath.Dir(fileName) diff --git a/pkg/io/serializable.go b/pkg/io/serializable.go index 43e659731..9bee4eab5 100644 --- a/pkg/io/serializable.go +++ b/pkg/io/serializable.go @@ -2,10 +2,10 @@ package io // Serializable defines the binary encoding/decoding interface. Errors are // returned via BinReader/BinWriter Err field. These functions must have safe -// behavior when passed BinReader/BinWriter with Err already set. Invocations +// behavior when the passed BinReader/BinWriter with Err is already set. Invocations // to these functions tend to be nested, with this mechanism only the top-level -// caller should handle the error once and all the other code should just not -// panic in presence of error. +// caller should handle an error once and all the other code should just not +// panic while there is an error. type Serializable interface { DecodeBinary(*BinReader) EncodeBinary(*BinWriter) diff --git a/pkg/io/size.go b/pkg/io/size.go index 9ee40eeba..75d0da195 100644 --- a/pkg/io/size.go +++ b/pkg/io/size.go @@ -35,7 +35,7 @@ func getVarIntSize(value int) int { } // GetVarSize returns the number of bytes in a serialized variable. It supports ints/uints (estimating -// them using variable-length encoding that is used in NEO), strings, pointers to Serializable structures, +// them with variable-length encoding that is used in NEO), strings, pointers to Serializable structures, // slices and arrays of ints/uints or Serializable structures. It's similar to GetVarSize(this T[] value) // used in C#, but differs in that it also supports things like Uint160 or Uint256. func GetVarSize(value interface{}) int { diff --git a/pkg/neotest/account.go b/pkg/neotest/account.go index d03db8d33..cbee806e6 100644 --- a/pkg/neotest/account.go +++ b/pkg/neotest/account.go @@ -2,7 +2,7 @@ package neotest var _nonce uint32 -// Nonce returns unique number that can be used as nonce for new transactions. +// Nonce returns a unique number that can be used as a nonce for new transactions. func Nonce() uint32 { _nonce++ return _nonce diff --git a/pkg/neotest/basic.go b/pkg/neotest/basic.go index 9ddfd72cf..dd9077887 100644 --- a/pkg/neotest/basic.go +++ b/pkg/neotest/basic.go @@ -35,7 +35,7 @@ type Executor struct { Contracts map[string]*Contract } -// NewExecutor creates new executor instance from provided blockchain and committee. +// NewExecutor creates a new executor instance from the provided blockchain and committee. func NewExecutor(t testing.TB, bc blockchainer.Blockchainer, validator, committee Signer) *Executor { checkMultiSigner(t, validator) checkMultiSigner(t, committee) @@ -49,28 +49,28 @@ func NewExecutor(t testing.TB, bc blockchainer.Blockchainer, validator, committe } } -// TopBlock returns block with the highest index. +// TopBlock returns the block with the highest index. func (e *Executor) TopBlock(t testing.TB) *block.Block { b, err := e.Chain.GetBlock(e.Chain.GetHeaderHash(int(e.Chain.BlockHeight()))) require.NoError(t, err) return b } -// NativeHash returns native contract hash by name. +// NativeHash returns a native contract hash by the name. func (e *Executor) NativeHash(t testing.TB, name string) util.Uint160 { h, err := e.Chain.GetNativeContractScriptHash(name) require.NoError(t, err) return h } -// ContractHash returns contract hash by ID. +// ContractHash returns a contract hash by the ID. func (e *Executor) ContractHash(t testing.TB, id int32) util.Uint160 { h, err := e.Chain.GetContractScriptHash(id) require.NoError(t, err) return h } -// NativeID returns native contract ID by name. +// NativeID returns a native contract ID by the name. func (e *Executor) NativeID(t testing.TB, name string) int32 { h := e.NativeHash(t, name) cs := e.Chain.GetContractState(h) @@ -78,7 +78,7 @@ func (e *Executor) NativeID(t testing.TB, name string) int32 { return cs.ID } -// NewUnsignedTx creates new unsigned transaction which invokes method of contract with hash. +// NewUnsignedTx creates a new unsigned transaction which invokes the method of the contract with the hash. func (e *Executor) NewUnsignedTx(t testing.TB, hash util.Uint160, method string, args ...interface{}) *transaction.Transaction { w := io.NewBufBinWriter() emit.AppCall(w.BinWriter, hash, method, callflag.All, args...) @@ -91,15 +91,15 @@ func (e *Executor) NewUnsignedTx(t testing.TB, hash util.Uint160, method string, return tx } -// NewTx creates new transaction which invokes contract method. -// Transaction is signed with signer. +// NewTx creates a new transaction which invokes the contract method. +// The transaction is signed by the signers. func (e *Executor) NewTx(t testing.TB, signers []Signer, hash util.Uint160, method string, args ...interface{}) *transaction.Transaction { tx := e.NewUnsignedTx(t, hash, method, args...) return e.SignTx(t, tx, -1, signers...) } -// SignTx signs a transaction using provided signers. +// SignTx signs a transaction using the provided signers. func (e *Executor) SignTx(t testing.TB, tx *transaction.Transaction, sysFee int64, signers ...Signer) *transaction.Transaction { for _, acc := range signers { tx.Signers = append(tx.Signers, transaction.Signer{ @@ -116,7 +116,7 @@ func (e *Executor) SignTx(t testing.TB, tx *transaction.Transaction, sysFee int6 return tx } -// NewAccount returns new signer holding 100.0 GAS (or given amount is specified). +// NewAccount returns a new signer holding 100.0 GAS (or given amount is specified). // This method advances the chain by one block with a transfer transaction. func (e *Executor) NewAccount(t testing.TB, expectedGASBalance ...int64) Signer { acc, err := wallet.NewAccount() @@ -134,24 +134,24 @@ func (e *Executor) NewAccount(t testing.TB, expectedGASBalance ...int64) Signer return NewSingleSigner(acc) } -// DeployContract compiles and deploys contract to bc. It also checks that -// precalculated contract hash matches the actual one. +// DeployContract compiles and deploys a contract to the bc. It also checks that +// the precalculated contract hash matches the actual one. // data is an optional argument to `_deploy`. -// Returns hash of the deploy transaction. +// It returns the hash of the deploy transaction. func (e *Executor) DeployContract(t testing.TB, c *Contract, data interface{}) util.Uint256 { return e.DeployContractBy(t, e.Validator, c, data) } -// DeployContractBy compiles and deploys contract to bc using provided signer. -// It also checks that precalculated contract hash matches the actual one. +// DeployContractBy compiles and deploys a contract to the bc using the provided signer. +// It also checks that the precalculated contract hash matches the actual one. // data is an optional argument to `_deploy`. -// Returns hash of the deploy transaction. +// It returns the hash of the deploy transaction. func (e *Executor) DeployContractBy(t testing.TB, signer Signer, c *Contract, data interface{}) util.Uint256 { tx := NewDeployTxBy(t, e.Chain, signer, c, data) e.AddNewBlock(t, tx) e.CheckHalt(t, tx.Hash()) - // Check that precalculated hash matches the real one. + // Check that the precalculated hash matches the real one. e.CheckTxNotificationEvent(t, tx.Hash(), -1, state.NotificationEvent{ ScriptHash: e.NativeHash(t, nativenames.Management), Name: "Deploy", @@ -163,15 +163,15 @@ func (e *Executor) DeployContractBy(t testing.TB, signer Signer, c *Contract, da return tx.Hash() } -// DeployContractCheckFAULT compiles and deploys contract to bc using validator -// account. It checks that deploy transaction FAULTed with the specified error. +// DeployContractCheckFAULT compiles and deploys a contract to the bc using the validator +// account. It checks that the deploy transaction FAULTed with the specified error. func (e *Executor) DeployContractCheckFAULT(t testing.TB, c *Contract, data interface{}, errMessage string) { tx := e.NewDeployTx(t, e.Chain, c, data) e.AddNewBlock(t, tx) e.CheckFault(t, tx.Hash(), errMessage) } -// InvokeScript adds transaction with the specified script to the chain and +// InvokeScript adds a transaction with the specified script to the chain and // returns its hash. It does no faults check. func (e *Executor) InvokeScript(t testing.TB, script []byte, signers []Signer) util.Uint256 { tx := e.PrepareInvocation(t, script, signers) @@ -179,7 +179,7 @@ func (e *Executor) InvokeScript(t testing.TB, script []byte, signers []Signer) u return tx.Hash() } -// PrepareInvocation creates transaction with the specified script and signs it +// PrepareInvocation creates a transaction with the specified script and signs it // by the provided signer. func (e *Executor) PrepareInvocation(t testing.TB, script []byte, signers []Signer, validUntilBlock ...uint32) *transaction.Transaction { tx := transaction.New(script, 0) @@ -192,21 +192,21 @@ func (e *Executor) PrepareInvocation(t testing.TB, script []byte, signers []Sign return tx } -// InvokeScriptCheckHALT adds transaction with the specified script to the chain -// and checks it's HALTed with the specified items on stack. +// InvokeScriptCheckHALT adds a transaction with the specified script to the chain +// and checks if it's HALTed with the specified items on stack. func (e *Executor) InvokeScriptCheckHALT(t testing.TB, script []byte, signers []Signer, stack ...stackitem.Item) { hash := e.InvokeScript(t, script, signers) e.CheckHalt(t, hash, stack...) } -// InvokeScriptCheckFAULT adds transaction with the specified script to the -// chain and checks it's FAULTed with the specified error. +// InvokeScriptCheckFAULT adds a transaction with the specified script to the +// chain and checks if it's FAULTed with the specified error. func (e *Executor) InvokeScriptCheckFAULT(t testing.TB, script []byte, signers []Signer, errMessage string) { hash := e.InvokeScript(t, script, signers) e.CheckFault(t, hash, errMessage) } -// CheckHalt checks that transaction persisted with HALT state. +// CheckHalt checks that the transaction is persisted with HALT state. func (e *Executor) CheckHalt(t testing.TB, h util.Uint256, stack ...stackitem.Item) *state.AppExecResult { aer, err := e.Chain.GetAppExecResults(h, trigger.Application) require.NoError(t, err) @@ -217,8 +217,8 @@ func (e *Executor) CheckHalt(t testing.TB, h util.Uint256, stack ...stackitem.It return &aer[0] } -// CheckFault checks that transaction persisted with FAULT state. -// Raised exception is also checked to contain s as a substring. +// CheckFault checks that the transaction is persisted with FAULT state. +// The raised exception is also checked to contain the s as a substring. func (e *Executor) CheckFault(t testing.TB, h util.Uint256, s string) { aer, err := e.Chain.GetAppExecResults(h, trigger.Application) require.NoError(t, err) @@ -227,7 +227,7 @@ func (e *Executor) CheckFault(t testing.TB, h util.Uint256, s string) { "expected: %s, got: %s", s, aer[0].FaultException) } -// CheckTxNotificationEvent checks that specified event was emitted at the specified position +// CheckTxNotificationEvent checks that the specified event was emitted at the specified position // during transaction script execution. Negative index corresponds to backwards enumeration. func (e *Executor) CheckTxNotificationEvent(t testing.TB, h util.Uint256, index int, expected state.NotificationEvent) { aer, err := e.Chain.GetAppExecResults(h, trigger.Application) @@ -240,24 +240,24 @@ func (e *Executor) CheckTxNotificationEvent(t testing.TB, h util.Uint256, index require.Equal(t, expected, aer[0].Events[index]) } -// CheckGASBalance ensures that provided account owns specified amount of GAS. +// CheckGASBalance ensures that the provided account owns the specified amount of GAS. func (e *Executor) CheckGASBalance(t testing.TB, acc util.Uint160, expected *big.Int) { actual := e.Chain.GetUtilityTokenBalance(acc) require.Equal(t, expected, actual, fmt.Errorf("invalid GAS balance: expected %s, got %s", expected.String(), actual.String())) } -// EnsureGASBalance ensures that provided account owns amount of GAS that satisfies provided condition. +// EnsureGASBalance ensures that the provided account owns the amount of GAS that satisfies the provided condition. func (e *Executor) EnsureGASBalance(t testing.TB, acc util.Uint160, isOk func(balance *big.Int) bool) { actual := e.Chain.GetUtilityTokenBalance(acc) require.True(t, isOk(actual), fmt.Errorf("invalid GAS balance: got %s, condition is not satisfied", actual.String())) } -// NewDeployTx returns new deployment tx for contract signed by committee. +// NewDeployTx returns a new deployment tx for the contract signed by the committee. func (e *Executor) NewDeployTx(t testing.TB, bc blockchainer.Blockchainer, c *Contract, data interface{}) *transaction.Transaction { return NewDeployTxBy(t, bc, e.Validator, c, data) } -// NewDeployTxBy returns new deployment tx for contract signed by the specified signer. +// NewDeployTxBy returns a new deployment tx for the contract signed by the specified signer. func NewDeployTxBy(t testing.TB, bc blockchainer.Blockchainer, signer Signer, c *Contract, data interface{}) *transaction.Transaction { rawManifest, err := json.Marshal(c.Manifest) require.NoError(t, err) @@ -304,7 +304,7 @@ func AddNetworkFee(bc blockchainer.Blockchainer, tx *transaction.Transaction, si tx.NetworkFee += int64(size) * bc.FeePerByte() } -// NewUnsignedBlock creates new unsigned block from txs. +// NewUnsignedBlock creates a new unsigned block from txs. func (e *Executor) NewUnsignedBlock(t testing.TB, txs ...*transaction.Transaction) *block.Block { lastBlock := e.TopBlock(t) b := &block.Block{ @@ -327,7 +327,7 @@ func (e *Executor) NewUnsignedBlock(t testing.TB, txs ...*transaction.Transactio return b } -// AddNewBlock creates a new block from provided transactions and adds it on bc. +// AddNewBlock creates a new block from the provided transactions and adds it on the bc. func (e *Executor) AddNewBlock(t testing.TB, txs ...*transaction.Transaction) *block.Block { b := e.NewUnsignedBlock(t, txs...) e.SignBlock(b) @@ -335,7 +335,7 @@ func (e *Executor) AddNewBlock(t testing.TB, txs ...*transaction.Transaction) *b return b } -// GenerateNewBlocks adds specified number of empty blocks to the chain. +// GenerateNewBlocks adds the specified number of empty blocks to the chain. func (e *Executor) GenerateNewBlocks(t testing.TB, count int) []*block.Block { blocks := make([]*block.Block, count) for i := 0; i < count; i++ { @@ -360,7 +360,7 @@ func (e *Executor) AddBlockCheckHalt(t testing.TB, txs ...*transaction.Transacti return b } -// TestInvoke creates a test VM with dummy block and executes transaction in it. +// TestInvoke creates a test VM with a dummy block and executes a transaction in it. func TestInvoke(bc blockchainer.Blockchainer, tx *transaction.Transaction) (*vm.VM, error) { lastBlock, err := bc.GetBlock(bc.GetHeaderHash(int(bc.BlockHeight()))) if err != nil { @@ -373,8 +373,8 @@ func TestInvoke(bc blockchainer.Blockchainer, tx *transaction.Transaction) (*vm. }, } - // `GetTestVM` as well as `Run` can use transaction hash which will set cached value. - // This is unwanted behaviour so we explicitly copy transaction to perform execution. + // `GetTestVM` as well as `Run` can use a transaction hash which will set a cached value. + // This is unwanted behavior, so we explicitly copy the transaction to perform execution. ttx := *tx ic := bc.GetTestVM(trigger.Application, &ttx, b) defer ic.Finalize() @@ -384,14 +384,14 @@ func TestInvoke(bc blockchainer.Blockchainer, tx *transaction.Transaction) (*vm. return ic.VM, err } -// GetTransaction returns transaction and its height by the specified hash. +// GetTransaction returns a transaction and its height by the specified hash. func (e *Executor) GetTransaction(t testing.TB, h util.Uint256) (*transaction.Transaction, uint32) { tx, height, err := e.Chain.GetTransaction(h) require.NoError(t, err) return tx, height } -// GetBlockByIndex returns block by the specified index. +// GetBlockByIndex returns a block by the specified index. func (e *Executor) GetBlockByIndex(t testing.TB, idx int) *block.Block { h := e.Chain.GetHeaderHash(idx) require.NotEmpty(t, h) diff --git a/pkg/neotest/chain/chain.go b/pkg/neotest/chain/chain.go index a98b4c10b..1d675687d 100644 --- a/pkg/neotest/chain/chain.go +++ b/pkg/neotest/chain/chain.go @@ -29,21 +29,21 @@ const ( const singleValidatorWIF = "KxyjQ8eUa4FHt3Gvioyt1Wz29cTUrE4eTqX3yFSk1YFCsPL8uNsY" -// committeeWIFs is a list of unencrypted WIFs sorted by public key. +// committeeWIFs is a list of unencrypted WIFs sorted by the public key. var committeeWIFs = []string{ "KzfPUYDC9n2yf4fK5ro4C8KMcdeXtFuEnStycbZgX3GomiUsvX6W", "KzgWE3u3EDp13XPXXuTKZxeJ3Gi8Bsm8f9ijY3ZsCKKRvZUo1Cdn", singleValidatorWIF, "L2oEXKRAAMiPEZukwR5ho2S6SMeQLhcK9mF71ZnF7GvT8dU4Kkgz", - // Provide 2 committee extra members so that committee address differs from + // Provide 2 committee extra members so that the committee address differs from // the validators one. "L1Tr1iq5oz1jaFaMXP21sHDkJYDDkuLtpvQ4wRf1cjKvJYvnvpAb", "Kz6XTUrExy78q8f4MjDHnwz8fYYyUE8iPXwPRAkHa3qN2JcHYm7e", } var ( - // committeeAcc is an account used to sign tx as a committee. + // committeeAcc is an account used to sign a tx as a committee. committeeAcc *wallet.Account // multiCommitteeAcc contains committee accounts used in a multi-node setup. @@ -52,7 +52,7 @@ var ( // multiValidatorAcc contains validator accounts used in a multi-node setup. multiValidatorAcc []*wallet.Account - // standByCommittee contains list of committee public keys to use in config. + // standByCommittee contains a list of committee public keys to use in config. standByCommittee []string ) @@ -115,11 +115,11 @@ func init() { } } -// NewSingle creates new blockchain instance with a single validator and +// NewSingle creates a new blockchain instance with a single validator and // setups cleanup functions. The configuration used is with netmode.UnitTestNet -// magic, and SecondsPerBlock/MaxTraceableBlocks options defined by constants in +// magic and SecondsPerBlock/MaxTraceableBlocks options defined by constants in // this package. MemoryStore is used as the backend storage, so all of the chain -// contents is always in RAM. The Signer returned is validator (and committee at +// contents is always in RAM. The Signer returned is the validator (and the committee at // the same time). func NewSingle(t testing.TB) (*core.Blockchain, neotest.Signer) { return NewSingleWithCustomConfig(t, nil) @@ -133,9 +133,9 @@ func NewSingleWithCustomConfig(t testing.TB, f func(*config.ProtocolConfiguratio // NewSingleWithCustomConfigAndStore is similar to NewSingleWithCustomConfig, but // also allows to override backend Store being used. The last parameter controls if -// Run method is called on the Blockchain instance, if not then it's caller's -// responsibility to do that before using the chain and its caller's responsibility -// also to properly Close the chain when done. +// Run method is called on the Blockchain instance. If not, it is its caller's +// responsibility to do that before using the chain and +// to properly Close the chain when done. func NewSingleWithCustomConfigAndStore(t testing.TB, f func(cfg *config.ProtocolConfiguration), st storage.Store, run bool) (*core.Blockchain, neotest.Signer) { protoCfg := config.ProtocolConfiguration{ Magic: netmode.UnitTestNet, @@ -162,14 +162,14 @@ func NewSingleWithCustomConfigAndStore(t testing.TB, f func(cfg *config.Protocol return bc, neotest.NewMultiSigner(committeeAcc) } -// NewMulti creates new blockchain instance with four validators and six -// committee members, otherwise not differring much from NewSingle. The -// second value returned contains validators Signer, the third -- committee one. +// NewMulti creates a new blockchain instance with four validators and six +// committee members. Otherwise, it does not differ much from NewSingle. The +// second value returned contains the validators Signer, the third -- the committee one. func NewMulti(t testing.TB) (*core.Blockchain, neotest.Signer, neotest.Signer) { return NewMultiWithCustomConfig(t, nil) } -// NewMultiWithCustomConfig is similar to NewMulti except it allows to override the +// NewMultiWithCustomConfig is similar to NewMulti, except it allows to override the // default configuration. func NewMultiWithCustomConfig(t testing.TB, f func(*config.ProtocolConfiguration)) (*core.Blockchain, neotest.Signer, neotest.Signer) { return NewMultiWithCustomConfigAndStore(t, f, nil, true) @@ -177,9 +177,9 @@ func NewMultiWithCustomConfig(t testing.TB, f func(*config.ProtocolConfiguration // NewMultiWithCustomConfigAndStore is similar to NewMultiWithCustomConfig, but // also allows to override backend Store being used. The last parameter controls if -// Run method is called on the Blockchain instance, if not then it's caller's -// responsibility to do that before using the chain and its caller's responsibility -// also to properly Close the chain when done. +// Run method is called on the Blockchain instance. If not, it is its caller's +// responsibility to do that before using the chain and +// to properly Close the chain when done. func NewMultiWithCustomConfigAndStore(t testing.TB, f func(*config.ProtocolConfiguration), st storage.Store, run bool) (*core.Blockchain, neotest.Signer, neotest.Signer) { bc, validator, committee, err := NewMultiWithCustomConfigAndStoreNoCheck(t, f, st) require.NoError(t, err) diff --git a/pkg/neotest/chain/chain_test.go b/pkg/neotest/chain/chain_test.go index d8a85a21c..d69ceb530 100644 --- a/pkg/neotest/chain/chain_test.go +++ b/pkg/neotest/chain/chain_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" ) -// TestNewMulti checks that transaction and block is signed correctly for multi-node setup. +// TestNewMulti checks that the transaction and the block are signed correctly for multi-node setup. func TestNewMulti(t *testing.T) { bc, vAcc, cAcc := NewMulti(t) e := neotest.NewExecutor(t, bc, vAcc, cAcc) diff --git a/pkg/neotest/chain/doc.go b/pkg/neotest/chain/doc.go index 1b0d6f286..ac45ff52d 100644 --- a/pkg/neotest/chain/doc.go +++ b/pkg/neotest/chain/doc.go @@ -1,7 +1,7 @@ /* Package chain contains functions creating new test blockchain instances. Different configurations can be used, but all chains created here use -well-known keys. Most of the time single-node chain is the best choice to use -unless you specifically need multiple validators and large committee. +well-known keys. Most of the time, a single-node chain is the best choice to use +unless you specifically need multiple validators and a large committee. */ package chain diff --git a/pkg/neotest/client.go b/pkg/neotest/client.go index ba8aaf695..e35314655 100644 --- a/pkg/neotest/client.go +++ b/pkg/neotest/client.go @@ -12,14 +12,14 @@ import ( "github.com/stretchr/testify/require" ) -// ContractInvoker is a client for specific contract. +// ContractInvoker is a client for a specific contract. type ContractInvoker struct { *Executor Hash util.Uint160 Signers []Signer } -// NewInvoker creates new ContractInvoker for contract with hash h and specified signers. +// NewInvoker creates a new ContractInvoker for the contract with hash h and the specified signers. func (e *Executor) NewInvoker(h util.Uint160, signers ...Signer) *ContractInvoker { return &ContractInvoker{ Executor: e, @@ -28,7 +28,7 @@ func (e *Executor) NewInvoker(h util.Uint160, signers ...Signer) *ContractInvoke } } -// CommitteeInvoker creates new ContractInvoker for contract with hash h and committee multisignature signer. +// CommitteeInvoker creates a new ContractInvoker for the contract with hash h and a committee multisignature signer. func (e *Executor) CommitteeInvoker(h util.Uint160) *ContractInvoker { return &ContractInvoker{ Executor: e, @@ -37,7 +37,7 @@ func (e *Executor) CommitteeInvoker(h util.Uint160) *ContractInvoker { } } -// ValidatorInvoker creates new ContractInvoker for contract with hash h and validators multisignature signer. +// ValidatorInvoker creates a new ContractInvoker for the contract with hash h and a validators multisignature signer. func (e *Executor) ValidatorInvoker(h util.Uint160) *ContractInvoker { return &ContractInvoker{ Executor: e, @@ -46,7 +46,7 @@ func (e *Executor) ValidatorInvoker(h util.Uint160) *ContractInvoker { } } -// TestInvoke creates test VM and invokes method with args. +// TestInvoke creates test the VM and invokes the method with the args. func (c *ContractInvoker) TestInvoke(t testing.TB, method string, args ...interface{}) (*vm.Stack, error) { tx := c.PrepareInvokeNoSign(t, method, args...) b := c.NewUnsignedBlock(t, tx) @@ -58,24 +58,24 @@ func (c *ContractInvoker) TestInvoke(t testing.TB, method string, args ...interf return ic.VM.Estack(), err } -// WithSigners creates new client with the provided signer. +// WithSigners creates a new client with the provided signer. func (c *ContractInvoker) WithSigners(signers ...Signer) *ContractInvoker { newC := *c newC.Signers = signers return &newC } -// PrepareInvoke creates new invocation transaction. +// PrepareInvoke creates a new invocation transaction. func (c *ContractInvoker) PrepareInvoke(t testing.TB, method string, args ...interface{}) *transaction.Transaction { return c.Executor.NewTx(t, c.Signers, c.Hash, method, args...) } -// PrepareInvokeNoSign creates new unsigned invocation transaction. +// PrepareInvokeNoSign creates a new unsigned invocation transaction. func (c *ContractInvoker) PrepareInvokeNoSign(t testing.TB, method string, args ...interface{}) *transaction.Transaction { return c.Executor.NewUnsignedTx(t, c.Hash, method, args...) } -// Invoke invokes method with args, persists transaction and checks the result. +// Invoke invokes the method with the args, persists the transaction and checks the result. // Returns transaction hash. func (c *ContractInvoker) Invoke(t testing.TB, result interface{}, method string, args ...interface{}) util.Uint256 { tx := c.PrepareInvoke(t, method, args...) @@ -84,8 +84,8 @@ func (c *ContractInvoker) Invoke(t testing.TB, result interface{}, method string return tx.Hash() } -// InvokeAndCheck invokes method with args, persists transaction and checks the result -// using provided function. Returns transaction hash. +// InvokeAndCheck invokes the method with the args, persists the transaction and checks the result +// using the provided function. It returns the transaction hash. func (c *ContractInvoker) InvokeAndCheck(t testing.TB, checkResult func(t testing.TB, stack []stackitem.Item), method string, args ...interface{}) util.Uint256 { tx := c.PrepareInvoke(t, method, args...) c.AddNewBlock(t, tx) @@ -98,7 +98,7 @@ func (c *ContractInvoker) InvokeAndCheck(t testing.TB, checkResult func(t testin return tx.Hash() } -// InvokeWithFeeFail is like InvokeFail but sets custom system fee for the transaction. +// InvokeWithFeeFail is like InvokeFail but sets the custom system fee for the transaction. func (c *ContractInvoker) InvokeWithFeeFail(t testing.TB, message string, sysFee int64, method string, args ...interface{}) util.Uint256 { tx := c.PrepareInvokeNoSign(t, method, args...) c.Executor.SignTx(t, tx, sysFee, c.Signers...) @@ -107,8 +107,8 @@ func (c *ContractInvoker) InvokeWithFeeFail(t testing.TB, message string, sysFee return tx.Hash() } -// InvokeFail invokes method with args, persists transaction and checks the error message. -// Returns transaction hash. +// InvokeFail invokes the method with the args, persists the transaction and checks the error message. +// It returns the transaction hash. func (c *ContractInvoker) InvokeFail(t testing.TB, message string, method string, args ...interface{}) { tx := c.PrepareInvoke(t, method, args...) c.AddNewBlock(t, tx) diff --git a/pkg/neotest/compile.go b/pkg/neotest/compile.go index 4679ec269..fee77c17e 100644 --- a/pkg/neotest/compile.go +++ b/pkg/neotest/compile.go @@ -21,10 +21,10 @@ type Contract struct { Manifest *manifest.Manifest } -// contracts caches compiled contracts from FS across multiple tests. +// contracts caches the compiled contracts from FS across multiple tests. var contracts = make(map[string]*Contract) -// CompileSource compiles contract from reader and returns it's NEF, manifest and hash. +// CompileSource compiles a contract from the reader and returns its NEF, manifest and hash. func CompileSource(t testing.TB, sender util.Uint160, src io.Reader, opts *compiler.Options) *Contract { // nef.NewFile() cares about version a lot. config.Version = "neotest" @@ -42,7 +42,7 @@ func CompileSource(t testing.TB, sender util.Uint160, src io.Reader, opts *compi } } -// CompileFile compiles contract from file and returns it's NEF, manifest and hash. +// CompileFile compiles a contract from the file and returns its NEF, manifest and hash. func CompileFile(t testing.TB, sender util.Uint160, srcPath string, configPath string) *Contract { if c, ok := contracts[srcPath]; ok { return c diff --git a/pkg/neotest/doc.go b/pkg/neotest/doc.go index a86dc4615..e288a9f41 100644 --- a/pkg/neotest/doc.go +++ b/pkg/neotest/doc.go @@ -1,15 +1,15 @@ /* -Package neotest contains framework for automated contract testing. +Package neotest contains a framework for automated contract testing. It can be used to implement unit-tests for contracts in Go using regular Go conventions. Usually it's used like this: - * an instance of blockchain is created using chain subpackage - * target contract is compiled using one of Compile* functions - * and Executor is created for blockchain - * it's used to deploy contract with DeployContract + * an instance of the blockchain is created using chain subpackage + * the target contract is compiled using one of Compile* functions + * and Executor is created for the blockchain + * it's used to deploy a contract with DeployContract * CommitteeInvoker and/or ValidatorInvoker are then created to perform test invocations - * if needed NewAccount is used to create appropriate number of accounts for the test + * if needed, NewAccount is used to create an appropriate number of accounts for the test Higher-order methods provided in Executor and ContractInvoker hide the details of transaction creation for the most part, but there are lower-level methods as diff --git a/pkg/neotest/signer.go b/pkg/neotest/signer.go index e9f8ba9e3..04020554b 100644 --- a/pkg/neotest/signer.go +++ b/pkg/neotest/signer.go @@ -16,43 +16,43 @@ import ( "github.com/stretchr/testify/require" ) -// Signer is a generic interface which can be either simple- or multi-signature signer. +// Signer is a generic interface which can be either a simple- or multi-signature signer. type Signer interface { - // ScriptHash returns signer script hash. + // ScriptHash returns a signer script hash. Script() []byte - // Script returns signer verification script. + // Script returns a signer verification script. ScriptHash() util.Uint160 - // SignHashable returns invocation script for signing an item. + // SignHashable returns an invocation script for signing an item. SignHashable(uint32, hash.Hashable) []byte // SignTx signs a transaction. SignTx(netmode.Magic, *transaction.Transaction) error } -// SingleSigner is a generic interface for simple one-signature signer. +// SingleSigner is a generic interface for a simple one-signature signer. type SingleSigner interface { Signer - // Account returns underlying account which can be used to - // get public key and/or sign arbitrary things. + // Account returns the underlying account which can be used to + // get a public key and/or sign arbitrary things. Account() *wallet.Account } -// MultiSigner is the interface for multisignature signing account. +// MultiSigner is an interface for multisignature signing account. type MultiSigner interface { Signer - // Single returns simple-signature signer for n-th account in list. + // Single returns a simple-signature signer for the n-th account in a list. Single(n int) SingleSigner } -// signer represents simple-signature signer. +// signer represents a simple-signature signer. type signer wallet.Account -// multiSigner represents single multi-signature signer consisting of provided accounts. +// multiSigner represents a single multi-signature signer consisting of the provided accounts. type multiSigner struct { accounts []*wallet.Account m int } -// NewSingleSigner returns multi-signature signer for the provided account. +// NewSingleSigner returns a multi-signature signer for the provided account. // It must contain exactly as many accounts as needed to sign the script. func NewSingleSigner(acc *wallet.Account) SingleSigner { if !vm.IsSignatureContract(acc.Contract.Script) { @@ -87,7 +87,7 @@ func (s *signer) Account() *wallet.Account { return (*wallet.Account)(s) } -// NewMultiSigner returns multi-signature signer for the provided account. +// NewMultiSigner returns a multi-signature signer for the provided account. // It must contain at least as many accounts as needed to sign the script. func NewMultiSigner(accs ...*wallet.Account) MultiSigner { if len(accs) == 0 { diff --git a/pkg/network/blockqueue.go b/pkg/network/blockqueue.go index 992ea54c8..54de16106 100644 --- a/pkg/network/blockqueue.go +++ b/pkg/network/blockqueue.go @@ -8,7 +8,7 @@ import ( "go.uber.org/zap" ) -// Blockqueuer is the interface for block queue. +// Blockqueuer is an interface for a block queue. type Blockqueuer interface { AddBlock(block *block.Block) error AddHeaders(...*block.Header) error @@ -28,8 +28,8 @@ type blockQueue struct { } const ( - // blockCacheSize is the amount of blocks above current height - // which are stored in queue. + // blockCacheSize is the amount of blocks above the current height + // which are stored in the queue. blockCacheSize = 2000 ) @@ -80,7 +80,7 @@ func (bq *blockQueue) run() { err := bq.chain.AddBlock(b) if err != nil { - // The block might already be added by consensus. + // The block might already be added by the consensus. if bq.chain.BlockHeight() < b.Index { bq.log.Warn("blockQueue: failed adding block into the blockchain", zap.String("error", err.Error()), @@ -115,7 +115,7 @@ func (bq *blockQueue) putBlock(block *block.Block) error { return nil } pos := indexToPosition(block.Index) - // If we already have it, keep the old block, throw away new one. + // If we already have it, keep the old block, throw away the new one. if bq.queue[pos] == nil || bq.queue[pos].Index < block.Index { bq.len++ bq.queue[pos] = block diff --git a/pkg/network/blockqueue_test.go b/pkg/network/blockqueue_test.go index 137928c72..f647ebd0f 100644 --- a/pkg/network/blockqueue_test.go +++ b/pkg/network/blockqueue_test.go @@ -26,7 +26,7 @@ func TestBlockQueue(t *testing.T) { // nothing should be put into the blockchain assert.Equal(t, uint32(0), chain.BlockHeight()) assert.Equal(t, 2, bq.length()) - // now added expected ones (with duplicates) + // now added the expected ones (with duplicates) for i := 1; i < 5; i++ { assert.NoError(t, bq.putBlock(blocks[i])) } diff --git a/pkg/network/capability/capability.go b/pkg/network/capability/capability.go index 32073129f..8a65800a1 100644 --- a/pkg/network/capability/capability.go +++ b/pkg/network/capability/capability.go @@ -12,18 +12,18 @@ const MaxCapabilities = 32 // Capabilities is a list of Capability. type Capabilities []Capability -// DecodeBinary implements Serializable interface. +// DecodeBinary implements io.Serializable. func (cs *Capabilities) DecodeBinary(br *io.BinReader) { br.ReadArray(cs, MaxCapabilities) br.Err = cs.checkUniqueCapabilities() } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements io.Serializable. func (cs *Capabilities) EncodeBinary(br *io.BinWriter) { br.WriteArray(*cs) } -// checkUniqueCapabilities checks whether payload capabilities have unique type. +// checkUniqueCapabilities checks whether payload capabilities have a unique type. func (cs Capabilities) checkUniqueCapabilities() error { err := errors.New("capabilities with the same type are not allowed") var isFullNode, isTCP, isWS bool @@ -49,13 +49,13 @@ func (cs Capabilities) checkUniqueCapabilities() error { return nil } -// Capability describes network service available for node. +// Capability describes a network service available for the node. type Capability struct { Type Type Data io.Serializable } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements io.Serializable. func (c *Capability) DecodeBinary(br *io.BinReader) { c.Type = Type(br.ReadB()) switch c.Type { @@ -70,7 +70,7 @@ func (c *Capability) DecodeBinary(br *io.BinReader) { c.Data.DecodeBinary(br) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements io.Serializable. func (c *Capability) EncodeBinary(bw *io.BinWriter) { if c.Data == nil { bw.Err = errors.New("capability has no data") @@ -80,33 +80,33 @@ func (c *Capability) EncodeBinary(bw *io.BinWriter) { c.Data.EncodeBinary(bw) } -// Node represents full node capability with start height. +// Node represents full node capability with a start height. type Node struct { StartHeight uint32 } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements io.Serializable. func (n *Node) DecodeBinary(br *io.BinReader) { n.StartHeight = br.ReadU32LE() } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements io.Serializable. func (n *Node) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(n.StartHeight) } -// Server represents TCP or WS server capability with port. +// Server represents TCP or WS server capability with a port. type Server struct { // Port is the port this server is listening on. Port uint16 } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements io.Serializable. func (s *Server) DecodeBinary(br *io.BinReader) { s.Port = br.ReadU16LE() } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements io.Serializable. func (s *Server) EncodeBinary(bw *io.BinWriter) { bw.WriteU16LE(s.Port) } diff --git a/pkg/network/discovery.go b/pkg/network/discovery.go index 1a56b703f..f3fbc557b 100644 --- a/pkg/network/discovery.go +++ b/pkg/network/discovery.go @@ -28,7 +28,7 @@ type Discoverer interface { GoodPeers() []AddressWithCapabilities } -// AddressWithCapabilities represents node address with its capabilities. +// AddressWithCapabilities represents a node address with its capabilities. type AddressWithCapabilities struct { Address string Capabilities capability.Capabilities @@ -73,7 +73,7 @@ func newDefaultDiscovery(addrs []string, dt time.Duration, ts Transporter) Disco return NewDefaultDiscovery(addrs, dt, ts) } -// BackFill implements the Discoverer interface and will backfill the +// BackFill implements the Discoverer interface and will backfill // the pool with the given addresses. func (d *DefaultDiscovery) BackFill(addrs ...string) { d.lock.Lock() @@ -88,12 +88,12 @@ func (d *DefaultDiscovery) BackFill(addrs ...string) { d.lock.Unlock() } -// PoolCount returns the number of available node addresses. +// PoolCount returns the number of the available node addresses. func (d *DefaultDiscovery) PoolCount() int { return len(d.pool) } -// pushToPoolOrDrop tries to push address given into the pool, but if the pool +// pushToPoolOrDrop tries to push the address given into the pool, but if the pool // is already full, it just drops it. func (d *DefaultDiscovery) pushToPoolOrDrop(addr string) { select { @@ -165,7 +165,7 @@ func (d *DefaultDiscovery) GoodPeers() []AddressWithCapabilities { return addrs } -// RegisterGoodAddr registers good known connected address that passed +// RegisterGoodAddr registers a known good connected address that has passed // handshake successfully. func (d *DefaultDiscovery) RegisterGoodAddr(s string, c capability.Capabilities) { d.lock.Lock() @@ -174,15 +174,15 @@ func (d *DefaultDiscovery) RegisterGoodAddr(s string, c capability.Capabilities) d.lock.Unlock() } -// UnregisterConnectedAddr tells discoverer that this address is no longer -// connected, but it still is considered as good one. +// UnregisterConnectedAddr tells the discoverer that this address is no longer +// connected, but it is still considered a good one. func (d *DefaultDiscovery) UnregisterConnectedAddr(s string) { d.lock.Lock() delete(d.connectedAddrs, s) d.lock.Unlock() } -// RegisterConnectedAddr tells discoverer that given address is now connected. +// RegisterConnectedAddr tells discoverer that the given address is now connected. func (d *DefaultDiscovery) RegisterConnectedAddr(addr string) { d.lock.Lock() delete(d.unconnectedAddrs, addr) @@ -201,7 +201,7 @@ func (d *DefaultDiscovery) tryAddress(addr string) { } } -// Close stops discoverer pool processing making discoverer almost useless. +// Close stops discoverer pool processing, which makes the discoverer almost useless. func (d *DefaultDiscovery) Close() { d.closeMtx.Lock() d.isDead = true diff --git a/pkg/network/extpool/pool.go b/pkg/network/extpool/pool.go index b6c4cd3e8..5d172f6c2 100644 --- a/pkg/network/extpool/pool.go +++ b/pkg/network/extpool/pool.go @@ -18,17 +18,17 @@ type Ledger interface { VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) } -// Pool represents pool of extensible payloads. +// Pool represents a pool of extensible payloads. type Pool struct { lock sync.RWMutex verified map[util.Uint256]*list.Element senders map[util.Uint160]*list.List - // singleCap represents maximum number of payloads from the single sender. + // singleCap represents the maximum number of payloads from a single sender. singleCap int chain Ledger } -// New returns new payload pool using provided chain. +// New returns a new payload pool using the provided chain. func New(bc Ledger, capacity int) *Pool { if capacity <= 0 { panic("invalid capacity") @@ -47,9 +47,9 @@ var ( errInvalidHeight = errors.New("invalid height") ) -// Add adds extensible payload to the pool. -// First return value specifies if payload was new. -// Second one is nil if and only if payload is valid. +// Add adds an extensible payload to the pool. +// First return value specifies if the payload was new. +// Second one is nil if and only if the payload is valid. func (p *Pool) Add(e *payload.Extensible) (bool, error) { if ok, err := p.verify(e); err != nil || !ok { return ok, err @@ -82,8 +82,8 @@ func (p *Pool) verify(e *payload.Extensible) (bool, error) { } h := p.chain.BlockHeight() if h < e.ValidBlockStart || e.ValidBlockEnd <= h { - // We can receive consensus payload for the last or next block - // which leads to unwanted node disconnect. + // We can receive a consensus payload for the last or next block + // which leads to an unwanted node disconnect. if e.ValidBlockEnd == h { return false, nil } diff --git a/pkg/network/message.go b/pkg/network/message.go index fb605c8a7..4655c3be5 100644 --- a/pkg/network/message.go +++ b/pkg/network/message.go @@ -15,12 +15,12 @@ import ( // CompressionMinSize is the lower bound to apply compression. const CompressionMinSize = 1024 -// Message is the complete message send between nodes. +// Message is a complete message sent between nodes. type Message struct { // Flags that represents whether a message is compressed. // 0 for None, 1 for Compressed. Flags MessageFlag - // Command is byte command code. + // Command is a byte command code. Command CommandType // Payload send with the message. @@ -29,12 +29,12 @@ type Message struct { // Compressed message payload. compressedPayload []byte - // StateRootInHeader specifies if state root is included in block header. + // StateRootInHeader specifies if the state root is included in the block header. // This is needed for correct decoding. StateRootInHeader bool } -// MessageFlag represents compression level of message payload. +// MessageFlag represents compression level of a message payload. type MessageFlag byte // Possible message flags. @@ -212,8 +212,8 @@ func (m *Message) Bytes() ([]byte, error) { return w.Bytes(), nil } -// tryCompressPayload sets message's compressed payload to serialized -// payload and compresses it in case if its size exceeds CompressionMinSize. +// tryCompressPayload sets the message's compressed payload to a serialized +// payload and compresses it in case its size exceeds CompressionMinSize. func (m *Message) tryCompressPayload() error { if m.Payload == nil { return nil diff --git a/pkg/network/metrics/metrics.go b/pkg/network/metrics/metrics.go index 15a711618..088a8477e 100644 --- a/pkg/network/metrics/metrics.go +++ b/pkg/network/metrics/metrics.go @@ -22,7 +22,7 @@ type Config struct { Port string `yaml:"Port"` } -// Start runs http service with exposed endpoint on configured port. +// Start runs http service with the exposed endpoint on the configured port. func (ms *Service) Start() { if ms.config.Enabled { ms.log.Info("service is running", zap.String("endpoint", ms.Addr)) @@ -35,7 +35,7 @@ func (ms *Service) Start() { } } -// ShutDown stops service. +// ShutDown stops the service. func (ms *Service) ShutDown() { ms.log.Info("shutting down service", zap.String("endpoint", ms.Addr)) err := ms.Shutdown(context.Background()) diff --git a/pkg/network/metrics/pprof.go b/pkg/network/metrics/pprof.go index 13b853476..887acc0ea 100644 --- a/pkg/network/metrics/pprof.go +++ b/pkg/network/metrics/pprof.go @@ -10,7 +10,7 @@ import ( // PprofService https://golang.org/pkg/net/http/pprof/. type PprofService Service -// NewPprofService created new service for gathering pprof metrics. +// NewPprofService creates a new service for gathering pprof metrics. func NewPprofService(cfg Config, log *zap.Logger) *Service { if log == nil { return nil diff --git a/pkg/network/metrics/prometheus.go b/pkg/network/metrics/prometheus.go index 9bfe54205..c02bc50fb 100644 --- a/pkg/network/metrics/prometheus.go +++ b/pkg/network/metrics/prometheus.go @@ -10,7 +10,7 @@ import ( // PrometheusService https://prometheus.io/docs/guides/go-application. type PrometheusService Service -// NewPrometheusService creates new service for gathering prometheus metrics. +// NewPrometheusService creates a new service for gathering prometheus metrics. func NewPrometheusService(cfg Config, log *zap.Logger) *Service { if log == nil { return nil diff --git a/pkg/network/payload/address.go b/pkg/network/payload/address.go index 13e9e9743..05e45c548 100644 --- a/pkg/network/payload/address.go +++ b/pkg/network/payload/address.go @@ -31,21 +31,21 @@ func NewAddressAndTime(e *net.TCPAddr, t time.Time, c capability.Capabilities) * return &aat } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *AddressAndTime) DecodeBinary(br *io.BinReader) { p.Timestamp = br.ReadU32LE() br.ReadBytes(p.IP[:]) p.Capabilities.DecodeBinary(br) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *AddressAndTime) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(p.Timestamp) bw.WriteBytes(p.IP[:]) p.Capabilities.EncodeBinary(bw) } -// GetTCPAddress makes a string from IP and port specified in TCPCapability. +// GetTCPAddress makes a string from the IP and the port specified in TCPCapability. // It returns an error if there's no such capability. func (p *AddressAndTime) GetTCPAddress() (string, error) { var netip = make(net.IP, 16) @@ -77,7 +77,7 @@ func NewAddressList(n int) *AddressList { return &alist } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *AddressList) DecodeBinary(br *io.BinReader) { br.ReadArray(&p.Addrs, MaxAddrsCount) if len(p.Addrs) == 0 { @@ -85,7 +85,7 @@ func (p *AddressList) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *AddressList) EncodeBinary(bw *io.BinWriter) { bw.WriteArray(p.Addrs) } diff --git a/pkg/network/payload/extensible.go b/pkg/network/payload/extensible.go index 66891e7e7..1ca3c3c6d 100644 --- a/pkg/network/payload/extensible.go +++ b/pkg/network/payload/extensible.go @@ -11,15 +11,15 @@ import ( const maxExtensibleCategorySize = 32 -// Extensible represents payload containing arbitrary data. +// Extensible represents a payload containing arbitrary data. type Extensible struct { - // Category is payload type. + // Category is the payload type. Category string - // ValidBlockStart is starting height for payload to be valid. + // ValidBlockStart is the starting height for a payload to be valid. ValidBlockStart uint32 - // ValidBlockEnd is height after which payload becomes invalid. + // ValidBlockEnd is the height after which a payload becomes invalid. ValidBlockEnd uint32 - // Sender is payload sender or signer. + // Sender is the payload sender or signer. Sender util.Uint160 // Data is custom payload data. Data []byte @@ -31,7 +31,7 @@ type Extensible struct { var errInvalidPadding = errors.New("invalid padding") -// NewExtensible creates new extensible payload. +// NewExtensible creates a new extensible payload. func NewExtensible() *Extensible { return &Extensible{} } diff --git a/pkg/network/payload/getblockbyindex.go b/pkg/network/payload/getblockbyindex.go index 372af4d08..24f573014 100644 --- a/pkg/network/payload/getblockbyindex.go +++ b/pkg/network/payload/getblockbyindex.go @@ -12,7 +12,7 @@ type GetBlockByIndex struct { Count int16 } -// NewGetBlockByIndex returns GetBlockByIndex payload with specified start index and count. +// NewGetBlockByIndex returns GetBlockByIndex payload with the specified start index and count. func NewGetBlockByIndex(indexStart uint32, count int16) *GetBlockByIndex { return &GetBlockByIndex{ IndexStart: indexStart, @@ -20,7 +20,7 @@ func NewGetBlockByIndex(indexStart uint32, count int16) *GetBlockByIndex { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (d *GetBlockByIndex) DecodeBinary(br *io.BinReader) { d.IndexStart = br.ReadU32LE() d.Count = int16(br.ReadU16LE()) @@ -29,7 +29,7 @@ func (d *GetBlockByIndex) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (d *GetBlockByIndex) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(d.IndexStart) bw.WriteU16LE(uint16(d.Count)) diff --git a/pkg/network/payload/getblocks.go b/pkg/network/payload/getblocks.go index b881559a3..682fc0380 100644 --- a/pkg/network/payload/getblocks.go +++ b/pkg/network/payload/getblocks.go @@ -27,7 +27,7 @@ func NewGetBlocks(start util.Uint256, count int16) *GetBlocks { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *GetBlocks) DecodeBinary(br *io.BinReader) { p.HashStart.DecodeBinary(br) p.Count = int16(br.ReadU16LE()) @@ -36,7 +36,7 @@ func (p *GetBlocks) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *GetBlocks) EncodeBinary(bw *io.BinWriter) { p.HashStart.EncodeBinary(bw) bw.WriteU16LE(uint16(p.Count)) diff --git a/pkg/network/payload/headers.go b/pkg/network/payload/headers.go index b9b21c415..5d75279e0 100644 --- a/pkg/network/payload/headers.go +++ b/pkg/network/payload/headers.go @@ -11,22 +11,22 @@ import ( // Headers payload. type Headers struct { Hdrs []*block.Header - // StateRootInHeader specifies whether header contains state root. + // StateRootInHeader specifies whether the header contains a state root. StateRootInHeader bool } -// Users can at most request 2k header. +// Users can at most request 2k headers. const ( MaxHeadersAllowed = 2000 ) -// ErrTooManyHeaders is an error returned when too many headers were received. +// ErrTooManyHeaders is an error returned when too many headers have been received. var ErrTooManyHeaders = fmt.Errorf("too many headers were received (max: %d)", MaxHeadersAllowed) // ErrNoHeaders is returned for zero-elements Headers payload which is considered to be invalid. var ErrNoHeaders = errors.New("no headers (zero length array)") -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *Headers) DecodeBinary(br *io.BinReader) { lenHeaders := br.ReadVarUint() @@ -56,7 +56,7 @@ func (p *Headers) DecodeBinary(br *io.BinReader) { } } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *Headers) EncodeBinary(bw *io.BinWriter) { bw.WriteArray(p.Hdrs) } diff --git a/pkg/network/payload/inventory.go b/pkg/network/payload/inventory.go index 563ccdde1..04041e7b8 100644 --- a/pkg/network/payload/inventory.go +++ b/pkg/network/payload/inventory.go @@ -5,7 +5,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// The node can broadcast the object information it owns by this message. +// A node can broadcast the object information it owns by this message. // The message can be sent automatically or can be used to answer getblock messages. // InventoryType is the type of an object in the Inventory message. @@ -42,14 +42,14 @@ const ( // Inventory payload. type Inventory struct { - // Type if the object hash. + // Type of the object hash. Type InventoryType // A list of hashes. Hashes []util.Uint256 } -// NewInventory return a pointer to an Inventory. +// NewInventory returns a pointer to an Inventory. func NewInventory(typ InventoryType, hashes []util.Uint256) *Inventory { return &Inventory{ Type: typ, @@ -57,13 +57,13 @@ func NewInventory(typ InventoryType, hashes []util.Uint256) *Inventory { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *Inventory) DecodeBinary(br *io.BinReader) { p.Type = InventoryType(br.ReadB()) br.ReadArray(&p.Hashes, MaxHashesCount) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *Inventory) EncodeBinary(bw *io.BinWriter) { bw.WriteB(byte(p.Type)) bw.WriteArray(p.Hashes) diff --git a/pkg/network/payload/merkleblock.go b/pkg/network/payload/merkleblock.go index 888b34e92..027e37ad4 100644 --- a/pkg/network/payload/merkleblock.go +++ b/pkg/network/payload/merkleblock.go @@ -16,7 +16,7 @@ type MerkleBlock struct { Flags []byte } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (m *MerkleBlock) DecodeBinary(br *io.BinReader) { m.Header = &block.Header{} m.Header.DecodeBinary(br) @@ -34,7 +34,7 @@ func (m *MerkleBlock) DecodeBinary(br *io.BinReader) { m.Flags = br.ReadVarBytes((txCount + 7) / 8) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (m *MerkleBlock) EncodeBinary(bw *io.BinWriter) { m.Header.EncodeBinary(bw) diff --git a/pkg/network/payload/mptdata.go b/pkg/network/payload/mptdata.go index ba607a86b..687aa68eb 100644 --- a/pkg/network/payload/mptdata.go +++ b/pkg/network/payload/mptdata.go @@ -6,7 +6,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" ) -// MPTData represents the set of serialized MPT nodes. +// MPTData represents a set of serialized MPT nodes. type MPTData struct { Nodes [][]byte } diff --git a/pkg/network/payload/mptinventory.go b/pkg/network/payload/mptinventory.go index 66aaf5c02..320e6fe37 100644 --- a/pkg/network/payload/mptinventory.go +++ b/pkg/network/payload/mptinventory.go @@ -5,12 +5,12 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// MaxMPTHashesCount is the maximum number of requested MPT nodes hashes. +// MaxMPTHashesCount is the maximum number of the requested MPT nodes hashes. const MaxMPTHashesCount = 32 // MPTInventory payload. type MPTInventory struct { - // A list of requested MPT nodes hashes. + // A list of the requested MPT nodes hashes. Hashes []util.Uint256 } @@ -21,12 +21,12 @@ func NewMPTInventory(hashes []util.Uint256) *MPTInventory { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *MPTInventory) DecodeBinary(br *io.BinReader) { br.ReadArray(&p.Hashes, MaxMPTHashesCount) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *MPTInventory) EncodeBinary(bw *io.BinWriter) { bw.WriteArray(p.Hashes) } diff --git a/pkg/network/payload/notary_request.go b/pkg/network/payload/notary_request.go index 1222c0263..8c68efe8a 100644 --- a/pkg/network/payload/notary_request.go +++ b/pkg/network/payload/notary_request.go @@ -21,7 +21,7 @@ type P2PNotaryRequest struct { hash util.Uint256 } -// NewP2PNotaryRequestFromBytes decodes P2PNotaryRequest from the given bytes. +// NewP2PNotaryRequestFromBytes decodes a P2PNotaryRequest from the given bytes. func NewP2PNotaryRequestFromBytes(b []byte) (*P2PNotaryRequest, error) { req := &P2PNotaryRequest{} br := io.NewBinReaderFromBuf(b) @@ -63,7 +63,7 @@ func (r *P2PNotaryRequest) createHash() error { return nil } -// DecodeBinaryUnsigned reads payload from w excluding signature. +// DecodeBinaryUnsigned reads payload from the w excluding signature. func (r *P2PNotaryRequest) decodeHashableFields(br *io.BinReader) { r.MainTransaction = &transaction.Transaction{} r.FallbackTransaction = &transaction.Transaction{} @@ -77,7 +77,7 @@ func (r *P2PNotaryRequest) decodeHashableFields(br *io.BinReader) { } } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (r *P2PNotaryRequest) DecodeBinary(br *io.BinReader) { r.decodeHashableFields(br) if br.Err == nil { @@ -85,13 +85,13 @@ func (r *P2PNotaryRequest) DecodeBinary(br *io.BinReader) { } } -// encodeHashableFields writes payload to w excluding signature. +// encodeHashableFields writes payload to the w excluding signature. func (r *P2PNotaryRequest) encodeHashableFields(bw *io.BinWriter) { r.MainTransaction.EncodeBinary(bw) r.FallbackTransaction.EncodeBinary(bw) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (r *P2PNotaryRequest) EncodeBinary(bw *io.BinWriter) { r.encodeHashableFields(bw) r.Witness.EncodeBinary(bw) diff --git a/pkg/network/payload/payload.go b/pkg/network/payload/payload.go index 8fc3ef211..a47c14676 100644 --- a/pkg/network/payload/payload.go +++ b/pkg/network/payload/payload.go @@ -2,7 +2,7 @@ package payload import "github.com/nspcc-dev/neo-go/pkg/io" -// MaxSize is maximum payload size in decompressed form. +// MaxSize is the maximum payload size in decompressed form. const MaxSize = 0x02000000 // Payload is anything that can be binary encoded/decoded. @@ -19,8 +19,8 @@ func NewNullPayload() NullPayload { return NullPayload{} } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p NullPayload) DecodeBinary(r *io.BinReader) {} -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p NullPayload) EncodeBinary(w *io.BinWriter) {} diff --git a/pkg/network/payload/ping.go b/pkg/network/payload/ping.go index 51af5bf3a..656a58a9f 100644 --- a/pkg/network/payload/ping.go +++ b/pkg/network/payload/ping.go @@ -25,14 +25,14 @@ func NewPing(blockIndex uint32, nonce uint32) *Ping { } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *Ping) DecodeBinary(br *io.BinReader) { p.LastBlockIndex = br.ReadU32LE() p.Timestamp = br.ReadU32LE() p.Nonce = br.ReadU32LE() } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *Ping) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(p.LastBlockIndex) bw.WriteU32LE(p.Timestamp) diff --git a/pkg/network/payload/version.go b/pkg/network/payload/version.go index dee8650a1..3b333739c 100644 --- a/pkg/network/payload/version.go +++ b/pkg/network/payload/version.go @@ -8,7 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/network/capability" ) -// MaxUserAgentLength is the limit for user agent field. +// MaxUserAgentLength is the limit for the user agent field. const MaxUserAgentLength = 1024 // Version payload. @@ -19,7 +19,7 @@ type Version struct { Version uint32 // timestamp Timestamp uint32 - // it's used to distinguish the node from public IP + // it's used to distinguish several nodes using the same public IP (or different ones) Nonce uint32 // client id UserAgent []byte @@ -39,7 +39,7 @@ func NewVersion(magic netmode.Magic, id uint32, ua string, c []capability.Capabi } } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (p *Version) DecodeBinary(br *io.BinReader) { p.Magic = netmode.Magic(br.ReadU32LE()) p.Version = br.ReadU32LE() @@ -49,7 +49,7 @@ func (p *Version) DecodeBinary(br *io.BinReader) { p.Capabilities.DecodeBinary(br) } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (p *Version) EncodeBinary(bw *io.BinWriter) { bw.WriteU32LE(uint32(p.Magic)) bw.WriteU32LE(p.Version) diff --git a/pkg/network/peer.go b/pkg/network/peer.go index b2df6ff69..ca0127d9d 100644 --- a/pkg/network/peer.go +++ b/pkg/network/peer.go @@ -12,10 +12,10 @@ type Peer interface { RemoteAddr() net.Addr // PeerAddr returns the remote address that should be used to establish // a new connection to the node. It can differ from the RemoteAddr - // address in case where the remote node is a client and its current + // address in case the remote node is a client and its current // connection port is different from the one the other node should use - // to connect to it. It's only valid after the handshake is completed, - // before that it returns the same address as RemoteAddr. + // to connect to it. It's only valid after the handshake is completed. + // Before that, it returns the same address as RemoteAddr. PeerAddr() net.Addr Disconnect(error) @@ -24,9 +24,9 @@ type Peer interface { EnqueueMessage(*Message) error // EnqueuePacket is a blocking packet enqueuer, it doesn't return until - // it puts given packet into the queue. It accepts a slice of bytes that + // it puts the given packet into the queue. It accepts a slice of bytes that // can be shared with other queues (so that message marshalling can be - // done once for all peers). Does nothing is the peer is not yet + // done once for all peers). It does nothing if the peer has not yet // completed handshaking. EnqueuePacket(bool, []byte) error @@ -35,17 +35,17 @@ type Peer interface { EnqueueP2PMessage(*Message) error // EnqueueP2PPacket is a blocking packet enqueuer, it doesn't return until - // it puts given packet into the queue. It accepts a slice of bytes that + // it puts the given packet into the queue. It accepts a slice of bytes that // can be shared with other queues (so that message marshalling can be - // done once for all peers). Does nothing is the peer is not yet + // done once for all peers). It does nothing if the peer has not yet // completed handshaking. This queue is intended to be used for unicast // peer to peer communication that is more important than broadcasts - // (handled by EnqueuePacket), but less important than high-priority + // (handled by EnqueuePacket) but less important than high-priority // messages (handled by EnqueueHPPacket). EnqueueP2PPacket([]byte) error // EnqueueHPPacket is a blocking high priority packet enqueuer, it - // doesn't return until it puts given packet into the high-priority + // doesn't return until it puts the given packet into the high-priority // queue. EnqueueHPPacket(bool, []byte) error Version() *payload.Version diff --git a/pkg/network/server.go b/pkg/network/server.go index b7c6bb342..ed79ee54c 100644 --- a/pkg/network/server.go +++ b/pkg/network/server.go @@ -275,13 +275,13 @@ func (s *Server) AddService(svc Service) { s.services[svc.Name()] = svc } -// AddExtensibleService register a service that handles extensible payload of some kind. +// AddExtensibleService register a service that handles an extensible payload of some kind. func (s *Server) AddExtensibleService(svc Service, category string, handler func(*payload.Extensible) error) { s.extensHandlers[category] = handler s.AddService(svc) } -// AddExtensibleHPService registers a high-priority service that handles extensible payload of some kind. +// AddExtensibleHPService registers a high-priority service that handles an extensible payload of some kind. func (s *Server) AddExtensibleHPService(svc Service, category string, handler func(*payload.Extensible) error, txCallback func(*transaction.Transaction)) { s.txCallback = txCallback s.extensHighPrio = category @@ -299,7 +299,7 @@ func (s *Server) UnconnectedPeers() []string { return s.discovery.UnconnectedPeers() } -// BadPeers returns a list of peers the are flagged as "bad" peers. +// BadPeers returns a list of peers that are flagged as "bad" peers. func (s *Server) BadPeers() []string { return s.discovery.BadPeers() } @@ -432,9 +432,9 @@ func (s *Server) tryStartServices() { } } -// SubscribeForNotaryRequests adds given channel to a notary request event +// SubscribeForNotaryRequests adds the given channel to a notary request event // broadcasting, so when a new P2PNotaryRequest is received or an existing -// P2PNotaryRequest is removed from pool you'll receive it via this channel. +// P2PNotaryRequest is removed from the pool you'll receive it via this channel. // Make sure it's read from regularly as not reading these events might affect // other Server functions. // Ensure that P2PSigExtensions are enabled before calling this method. @@ -445,7 +445,7 @@ func (s *Server) SubscribeForNotaryRequests(ch chan<- mempoolevent.Event) { s.notaryRequestPool.SubscribeForTransactions(ch) } -// UnsubscribeFromNotaryRequests unsubscribes given channel from notary request +// UnsubscribeFromNotaryRequests unsubscribes the given channel from notary request // notifications, you can close it afterwards. Passing non-subscribed channel // is a no-op. // Ensure that P2PSigExtensions are enabled before calling this method. @@ -456,7 +456,7 @@ func (s *Server) UnsubscribeFromNotaryRequests(ch chan<- mempoolevent.Event) { s.notaryRequestPool.UnsubscribeFromTransactions(ch) } -// getPeers returns current list of peers connected to the server filtered by +// getPeers returns the current list of the peers connected to the server filtered by // isOK function if it's given. func (s *Server) getPeers(isOK func(Peer) bool) []Peer { s.lock.RLock() @@ -473,14 +473,14 @@ func (s *Server) getPeers(isOK func(Peer) bool) []Peer { return peers } -// PeerCount returns the number of current connected peers. +// PeerCount returns the number of the currently connected peers. func (s *Server) PeerCount() int { s.lock.RLock() defer s.lock.RUnlock() return len(s.peers) } -// HandshakedPeersCount returns the number of connected peers +// HandshakedPeersCount returns the number of the connected peers // which have already performed handshake. func (s *Server) HandshakedPeersCount() int { s.lock.RLock() @@ -497,7 +497,7 @@ func (s *Server) HandshakedPeersCount() int { return count } -// getVersionMsg returns current version message. +// getVersionMsg returns the current version message. func (s *Server) getVersionMsg() (*Message, error) { port, err := s.Port() if err != nil { @@ -532,8 +532,8 @@ func (s *Server) getVersionMsg() (*Message, error) { // IsInSync answers the question of whether the server is in sync with the // network or not (at least how the server itself sees it). The server operates // with the data that it has, the number of peers (that has to be more than -// minimum number) and height of these peers (our chain has to be not lower -// than 2/3 of our peers have). Ideally we would check for the highest of the +// minimum number) and the height of these peers (our chain has to be not lower +// than 2/3 of our peers have). Ideally, we would check for the highest of the // peers, but the problem is that they can lie to us and send whatever height // they want to. func (s *Server) IsInSync() bool { @@ -566,7 +566,7 @@ func (s *Server) IsInSync() bool { return peersNumber >= s.MinPeers && (3*notHigher > 2*peersNumber) // && s.bQueue.length() == 0 } -// When a peer sends out his version we reply with verack after validating +// When a peer sends out its version, we reply with verack after validating // the version. func (s *Server) handleVersionCmd(p Peer, version *payload.Version) error { err := p.HandleVersion(version) @@ -576,7 +576,7 @@ func (s *Server) handleVersionCmd(p Peer, version *payload.Version) error { if s.id == version.Nonce { return errIdenticalID } - // Make sure both server and peer are operating on + // Make sure both the server and the peer are operating on // the same network. if s.Net != version.Magic { return errInvalidNetwork @@ -599,7 +599,7 @@ func (s *Server) handleVersionCmd(p Peer, version *payload.Version) error { return p.SendVersionAck(NewMessage(CMDVerack, payload.NewNullPayload())) } -// handleBlockCmd processes the received block received from its peer. +// handleBlockCmd processes the block received from its peer. func (s *Server) handleBlockCmd(p Peer, block *block.Block) error { if s.stateSync.IsActive() { return s.bSyncQueue.putBlock(block) @@ -607,7 +607,7 @@ func (s *Server) handleBlockCmd(p Peer, block *block.Block) error { return s.bQueue.putBlock(block) } -// handlePing processes ping request. +// handlePing processes a ping request. func (s *Server) handlePing(p Peer, ping *payload.Ping) error { err := p.HandlePing(ping) if err != nil { @@ -654,7 +654,7 @@ func (s *Server) requestHeaders(p Peer) error { return p.EnqueueP2PMessage(NewMessage(CMDGetHeaders, pl)) } -// handlePing processes pong request. +// handlePing processes a pong request. func (s *Server) handlePong(p Peer, pong *payload.Ping) error { err := p.HandlePong(pong) if err != nil { @@ -818,8 +818,8 @@ func (s *Server) handleMPTDataCmd(p Peer, data *payload.MPTData) error { return s.stateSync.AddMPTNodes(data.Nodes) } -// requestMPTNodes requests specified MPT nodes from the peer or broadcasts -// request if peer is not specified. +// requestMPTNodes requests the specified MPT nodes from the peer or broadcasts +// request if no peer is specified. func (s *Server) requestMPTNodes(p Peer, itms []util.Uint256) error { if len(itms) == 0 { return nil @@ -916,7 +916,7 @@ func (s *Server) handleHeadersCmd(p Peer, h *payload.Headers) error { return s.stateSync.AddHeaders(h.Hdrs...) } -// handleExtensibleCmd processes received extensible payload. +// handleExtensibleCmd processes the received extensible payload. func (s *Server) handleExtensibleCmd(e *payload.Extensible) error { if !s.syncReached.Load() { return nil @@ -950,7 +950,7 @@ func (s *Server) advertiseExtensible(e *payload.Extensible) { } } -// handleTxCmd processes received transaction. +// handleTxCmd processes the received transaction. // It never returns an error. func (s *Server) handleTxCmd(tx *transaction.Transaction) error { // It's OK for it to fail for various reasons like tx already existing @@ -975,7 +975,7 @@ func (s *Server) handleTxCmd(tx *transaction.Transaction) error { return nil } -// handleP2PNotaryRequestCmd process received P2PNotaryRequest payload. +// handleP2PNotaryRequestCmd process the received P2PNotaryRequest payload. func (s *Server) handleP2PNotaryRequestCmd(r *payload.P2PNotaryRequest) error { if !s.chain.P2PSigExtensionsEnabled() { return errors.New("P2PNotaryRequestCMD was received, but P2PSignatureExtensions are disabled") @@ -986,7 +986,7 @@ func (s *Server) handleP2PNotaryRequestCmd(r *payload.P2PNotaryRequest) error { return nil } -// RelayP2PNotaryRequest adds given request to the pool and relays. It does not check +// RelayP2PNotaryRequest adds the given request to the pool and relays. It does not check // P2PSigExtensions enabled. func (s *Server) RelayP2PNotaryRequest(r *payload.P2PNotaryRequest) error { err := s.verifyAndPoolNotaryRequest(r) @@ -1025,7 +1025,7 @@ func (s *Server) broadcastP2PNotaryRequestPayload(_ *transaction.Transaction, da s.broadcastMessage(msg) } -// handleAddrCmd will process received addresses. +// handleAddrCmd will process the received addresses. func (s *Server) handleAddrCmd(p Peer, addrs *payload.AddressList) error { if !p.CanProcessAddr() { return errors.New("unexpected addr received") @@ -1058,15 +1058,15 @@ func (s *Server) handleGetAddrCmd(p Peer) error { } // requestBlocks sends a CMDGetBlockByIndex message to the peer -// to sync up in blocks. A maximum of maxBlockBatch will -// send at once. Two things we need to take care of: +// to sync up in blocks. A maximum of maxBlockBatch will be +// sent at once. There are two things we need to take care of: // 1. If possible, blocks should be fetched in parallel. // height..+500 to one peer, height+500..+1000 to another etc. -// 2. Every block must eventually be fetched even if peer sends no answer. -// Thus the following algorithm is used: +// 2. Every block must eventually be fetched even if the peer sends no answer. +// Thus, the following algorithm is used: // 1. Block range is divided into chunks of payload.MaxHashesCount. // 2. Send requests for chunk in increasing order. -// 3. After all requests were sent, request random height. +// 3. After all requests have been sent, request random height. func (s *Server) requestBlocks(bq Blockqueuer, p Peer) error { h := bq.BlockHeight() pl := getRequestBlocksPayload(p, h, &s.lastRequestedBlock) @@ -1226,7 +1226,7 @@ func (s *Server) tryInitStateSync() { } s.lock.RUnlock() if peersNumber >= s.MinPeers && len(heights) > 0 { - // choose the height of the median peer as current chain's height + // choose the height of the median peer as the current chain's height h := heights[len(heights)/2] err := s.stateSync.Init(h) if err != nil { @@ -1244,7 +1244,7 @@ func (s *Server) tryInitStateSync() { } } -// BroadcastExtensible add locally-generated Extensible payload to the pool +// BroadcastExtensible add a locally-generated Extensible payload to the pool // and advertises it to peers. func (s *Server) BroadcastExtensible(p *payload.Extensible) { _, err := s.extensiblePool.Add(p) @@ -1256,7 +1256,7 @@ func (s *Server) BroadcastExtensible(p *payload.Extensible) { s.advertiseExtensible(p) } -// RequestTx asks for given transactions from Server peers using GetData message. +// RequestTx asks for the given transactions from Server peers using GetData message. func (s *Server) RequestTx(hashes ...util.Uint256) { if len(hashes) == 0 { return @@ -1278,7 +1278,7 @@ func (s *Server) RequestTx(hashes ...util.Uint256) { } } -// iteratePeersWithSendMsg sends given message to all peers using two functions +// iteratePeersWithSendMsg sends the given message to all peers using two functions // passed, one is to send the message and the other is to filtrate peers (the // peer is considered invalid if it returns false). func (s *Server) iteratePeersWithSendMsg(msg *Message, send func(Peer, bool, []byte) error, peerOK func(Peer) bool) { @@ -1463,7 +1463,7 @@ func (s *Server) broadcastTxLoop() { } // Port returns a server port that should be used in P2P version exchange. In -// case if `AnnouncedPort` is set in the server.Config, the announced node port +// case `AnnouncedPort` is set in the server.Config, the announced node port // will be returned (e.g. consider the node running behind NAT). If `AnnouncedPort` // isn't set, the port returned may still differs from that of server.Config. func (s *Server) Port() (uint16, error) { diff --git a/pkg/network/server_config.go b/pkg/network/server_config.go index eff4c53fe..a415dde6e 100644 --- a/pkg/network/server_config.go +++ b/pkg/network/server_config.go @@ -11,17 +11,17 @@ import ( type ( // ServerConfig holds the server configuration. ServerConfig struct { - // MinPeers is the minimum number of peers for normal operation, - // when the node has less than this number of peers it tries to + // MinPeers is the minimum number of peers for normal operation. + // When a node has less than this number of peers, it tries to // connect with some new ones. MinPeers int - // AttemptConnPeers it the number of connection to try to + // AttemptConnPeers is the number of connection to try to // establish when the connection count drops below the MinPeers // value. AttemptConnPeers int - // MaxPeers it the maximum numbers of peers that can + // MaxPeers is the maximum number of peers that can // be connected to the server. MaxPeers int @@ -46,7 +46,7 @@ type ( // Relay determines whether the server is forwarding its inventory. Relay bool - // Seeds are a list of initial nodes used to establish connectivity. + // Seeds is a list of initial nodes used to establish connectivity. Seeds []string // Maximum duration a single dial may take. @@ -79,7 +79,7 @@ type ( // StateRootCfg is stateroot module configuration. StateRootCfg config.StateRoot - // ExtensiblePoolSize is size of the pool for extensible payloads from a single sender. + // ExtensiblePoolSize is the size of the pool for extensible payloads from a single sender. ExtensiblePoolSize int } ) diff --git a/pkg/network/tcp_peer.go b/pkg/network/tcp_peer.go index 26b99cdfa..e6016a72f 100644 --- a/pkg/network/tcp_peer.go +++ b/pkg/network/tcp_peer.go @@ -81,7 +81,7 @@ func NewTCPPeer(conn net.Conn, s *Server) *TCPPeer { } } -// putPacketIntoQueue puts given message into the given queue if the peer has +// putPacketIntoQueue puts the given message into the given queue if the peer has // done handshaking. func (p *TCPPeer) putPacketIntoQueue(queue chan<- []byte, block bool, msg []byte) error { if !p.Handshaked() { @@ -110,7 +110,7 @@ func (p *TCPPeer) EnqueuePacket(block bool, msg []byte) error { return p.putPacketIntoQueue(p.sendQ, block, msg) } -// putMessageIntoQueue serializes given Message and puts it into given queue if +// putMessageIntoQueue serializes the given Message and puts it into given queue if // the peer has done handshaking. func (p *TCPPeer) putMsgIntoQueue(queue chan<- []byte, msg *Message) error { b, err := msg.Bytes() @@ -154,7 +154,7 @@ func (p *TCPPeer) writeMsg(msg *Message) error { } // handleConn handles the read side of the connection, it should be started as -// a goroutine right after the new peer setup. +// a goroutine right after a new peer setup. func (p *TCPPeer) handleConn() { var err error @@ -162,7 +162,7 @@ func (p *TCPPeer) handleConn() { go p.handleQueues() go p.handleIncoming() - // When a new peer is connected we send out our version immediately. + // When a new peer is connected, we send out our version immediately. err = p.SendVersion() if err == nil { r := io.NewBinReaderFromIO(p.conn) @@ -435,14 +435,14 @@ func (p *TCPPeer) Version() *payload.Version { return p.version } -// LastBlockIndex returns last block index. +// LastBlockIndex returns the last block index. func (p *TCPPeer) LastBlockIndex() uint32 { p.lock.RLock() defer p.lock.RUnlock() return p.lastBlockIndex } -// SendPing sends a ping message to the peer and does appropriate accounting of +// SendPing sends a ping message to the peer and does an appropriate accounting of // outstanding pings and timeouts. func (p *TCPPeer) SendPing(msg *Message) error { if !p.Handshaked() { @@ -467,7 +467,7 @@ func (p *TCPPeer) HandlePing(ping *payload.Ping) error { return nil } -// HandlePong handles a pong message received from the peer and does appropriate +// HandlePong handles a pong message received from the peer and does an appropriate // accounting of outstanding pings and timeouts. func (p *TCPPeer) HandlePong(pong *payload.Ping) error { p.lock.Lock() @@ -484,8 +484,8 @@ func (p *TCPPeer) HandlePong(pong *payload.Ping) error { return nil } -// AddGetAddrSent increments internal outstanding getaddr requests counter. The -// peer can only send then one addr reply per getaddr request. +// AddGetAddrSent increments internal outstanding getaddr requests counter. Then, +// the peer can only send one addr reply per getaddr request. func (p *TCPPeer) AddGetAddrSent() { p.getAddrSent.Inc() } diff --git a/pkg/rpc/client/client.go b/pkg/rpc/client/client.go index 1337b6d52..48c7878e7 100644 --- a/pkg/rpc/client/client.go +++ b/pkg/rpc/client/client.go @@ -38,20 +38,20 @@ type Client struct { requestF func(*request.Raw) (*response.Raw, error) cacheLock sync.RWMutex - // cache stores RPC node related information client is bound to. + // cache stores RPC node related information the client is bound to. // cache is mostly filled in during Init(), but can also be updated // during regular Client lifecycle. cache cache latestReqID *atomic.Uint64 - // getNextRequestID returns ID to be used for subsequent request creation. - // It is defined on Client so that our testing code can override this method - // for the sake of more predictable request IDs generation behaviour. + // getNextRequestID returns an ID to be used for the subsequent request creation. + // It is defined on Client, so that our testing code can override this method + // for the sake of more predictable request IDs generation behavior. getNextRequestID func() uint64 } // Options defines options for the RPC client. -// All values are optional. If any duration is not specified +// All values are optional. If any duration is not specified, // a default of 4 seconds will be used. type Options struct { // Cert is a client-side certificate, it doesn't work at the moment along @@ -74,7 +74,7 @@ type cache struct { nativeHashes map[string]util.Uint160 } -// calculateValidUntilBlockCache stores cached number of validators and +// calculateValidUntilBlockCache stores a cached number of validators and // cache expiration value in blocks. type calculateValidUntilBlockCache struct { validatorsCount uint32 @@ -215,8 +215,8 @@ func (c *Client) makeHTTPRequest(r *request.Raw) (*response.Raw, error) { } defer resp.Body.Close() - // The node might send us proper JSON anyway, so look there first and if - // it parses, then it has more relevant data than HTTP error code. + // The node might send us a proper JSON anyway, so look there first and if + // it parses, it has more relevant data than HTTP error code. err = json.NewDecoder(resp.Body).Decode(raw) if err != nil { if resp.StatusCode != http.StatusOK { @@ -231,8 +231,8 @@ func (c *Client) makeHTTPRequest(r *request.Raw) (*response.Raw, error) { return raw, nil } -// Ping attempts to create a connection to the endpoint. -// and returns an error if there is one. +// Ping attempts to create a connection to the endpoint +// and returns an error if there is any. func (c *Client) Ping() error { conn, err := net.DialTimeout("tcp", c.endpoint.Host, defaultDialTimeout) if err != nil { diff --git a/pkg/rpc/client/helper.go b/pkg/rpc/client/helper.go index d69f9520e..88c6eee2e 100644 --- a/pkg/rpc/client/helper.go +++ b/pkg/rpc/client/helper.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// getInvocationError returns an error in case of bad VM state or empty stack. +// getInvocationError returns an error in case of bad VM state or an empty stack. func getInvocationError(result *result.Invoke) error { if result.State != "HALT" { return fmt.Errorf("invocation failed: %s", result.FaultException) @@ -23,7 +23,7 @@ func getInvocationError(result *result.Invoke) error { return nil } -// topBoolFromStack returns the top boolean value from stack. +// topBoolFromStack returns the top boolean value from the stack. func topBoolFromStack(st []stackitem.Item) (bool, error) { index := len(st) - 1 // top stack element is last in the array result, ok := st[index].Value().(bool) @@ -33,7 +33,7 @@ func topBoolFromStack(st []stackitem.Item) (bool, error) { return result, nil } -// topIntFromStack returns the top integer value from stack. +// topIntFromStack returns the top integer value from the stack. func topIntFromStack(st []stackitem.Item) (int64, error) { index := len(st) - 1 // top stack element is last in the array bi, err := st[index].TryInteger() @@ -43,7 +43,7 @@ func topIntFromStack(st []stackitem.Item) (int64, error) { return bi.Int64(), nil } -// topPublicKeysFromStack returns the top array of public keys from stack. +// topPublicKeysFromStack returns the top array of public keys from the stack. func topPublicKeysFromStack(st []stackitem.Item) (keys.PublicKeys, error) { index := len(st) - 1 // top stack element is last in the array var ( @@ -68,7 +68,7 @@ func topPublicKeysFromStack(st []stackitem.Item) (keys.PublicKeys, error) { return pks, nil } -// top string from stack returns the top string from stack. +// top string from stack returns the top string from the stack. func topStringFromStack(st []stackitem.Item) (string, error) { index := len(st) - 1 // top stack element is last in the array bs, err := st[index].TryBytes() @@ -78,7 +78,7 @@ func topStringFromStack(st []stackitem.Item) (string, error) { return string(bs), nil } -// topUint160FromStack returns the top util.Uint160 from stack. +// topUint160FromStack returns the top util.Uint160 from the stack. func topUint160FromStack(st []stackitem.Item) (util.Uint160, error) { index := len(st) - 1 // top stack element is last in the array bs, err := st[index].TryBytes() @@ -88,7 +88,7 @@ func topUint160FromStack(st []stackitem.Item) (util.Uint160, error) { return util.Uint160DecodeBytesBE(bs) } -// topMapFromStack returns the top stackitem.Map from stack. +// topMapFromStack returns the top stackitem.Map from the stack. func topMapFromStack(st []stackitem.Item) (*stackitem.Map, error) { index := len(st) - 1 // top stack element is last in the array if t := st[index].Type(); t != stackitem.MapT { @@ -97,7 +97,7 @@ func topMapFromStack(st []stackitem.Item) (*stackitem.Map, error) { return st[index].(*stackitem.Map), nil } -// topIterableFromStack returns top list of elements of `resultItemType` type from stack. +// topIterableFromStack returns top list of elements of `resultItemType` type from the stack. func topIterableFromStack(st []stackitem.Item, resultItemType interface{}) ([]interface{}, error) { index := len(st) - 1 // top stack element is last in the array if t := st[index].Type(); t != stackitem.InteropT { diff --git a/pkg/rpc/client/native.go b/pkg/rpc/client/native.go index 85a857ac3..314138e87 100644 --- a/pkg/rpc/client/native.go +++ b/pkg/rpc/client/native.go @@ -143,7 +143,7 @@ func (c *Client) NNSGetAllRecords(nnsHash util.Uint160, name string) ([]nns.Reco return rss, nil } -// GetNotaryServiceFeePerKey returns a reward per notary request key for designated +// GetNotaryServiceFeePerKey returns a reward per notary request key for the designated // notary nodes. It doesn't cache the result. func (c *Client) GetNotaryServiceFeePerKey() (int64, error) { notaryHash, err := c.GetNativeContractHash(nativenames.Notary) diff --git a/pkg/rpc/client/nep.go b/pkg/rpc/client/nep.go index 56dc65f3b..3afc79bd2 100644 --- a/pkg/rpc/client/nep.go +++ b/pkg/rpc/client/nep.go @@ -8,7 +8,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/wallet" ) -// nepDecimals invokes `decimals` NEP* method on a specified contract. +// nepDecimals invokes `decimals` NEP* method on the specified contract. func (c *Client) nepDecimals(tokenHash util.Uint160) (int64, error) { result, err := c.InvokeFunction(tokenHash, "decimals", []smartcontract.Parameter{}, nil) if err != nil { @@ -22,7 +22,7 @@ func (c *Client) nepDecimals(tokenHash util.Uint160) (int64, error) { return topIntFromStack(result.Stack) } -// nepSymbol invokes `symbol` NEP* method on a specified contract. +// nepSymbol invokes `symbol` NEP* method on the specified contract. func (c *Client) nepSymbol(tokenHash util.Uint160) (string, error) { result, err := c.InvokeFunction(tokenHash, "symbol", []smartcontract.Parameter{}, nil) if err != nil { @@ -36,7 +36,7 @@ func (c *Client) nepSymbol(tokenHash util.Uint160) (string, error) { return topStringFromStack(result.Stack) } -// nepTotalSupply invokes `totalSupply` NEP* method on a specified contract. +// nepTotalSupply invokes `totalSupply` NEP* method on the specified contract. func (c *Client) nepTotalSupply(tokenHash util.Uint160) (int64, error) { result, err := c.InvokeFunction(tokenHash, "totalSupply", []smartcontract.Parameter{}, nil) if err != nil { @@ -50,7 +50,7 @@ func (c *Client) nepTotalSupply(tokenHash util.Uint160) (int64, error) { return topIntFromStack(result.Stack) } -// nepBalanceOf invokes `balanceOf` NEP* method on a specified contract. +// nepBalanceOf invokes `balanceOf` NEP* method on the specified contract. func (c *Client) nepBalanceOf(tokenHash, acc util.Uint160, tokenID []byte) (int64, error) { params := []smartcontract.Parameter{{ Type: smartcontract.Hash160Type, diff --git a/pkg/rpc/client/nep11.go b/pkg/rpc/client/nep11.go index 40217f517..f7dd5150f 100644 --- a/pkg/rpc/client/nep11.go +++ b/pkg/rpc/client/nep11.go @@ -16,22 +16,22 @@ import ( "github.com/nspcc-dev/neo-go/pkg/wallet" ) -// NEP11Decimals invokes `decimals` NEP-11 method on a specified contract. +// NEP11Decimals invokes `decimals` NEP-11 method on the specified contract. func (c *Client) NEP11Decimals(tokenHash util.Uint160) (int64, error) { return c.nepDecimals(tokenHash) } -// NEP11Symbol invokes `symbol` NEP-11 method on a specified contract. +// NEP11Symbol invokes `symbol` NEP-11 method on the specified contract. func (c *Client) NEP11Symbol(tokenHash util.Uint160) (string, error) { return c.nepSymbol(tokenHash) } -// NEP11TotalSupply invokes `totalSupply` NEP-11 method on a specified contract. +// NEP11TotalSupply invokes `totalSupply` NEP-11 method on the specified contract. func (c *Client) NEP11TotalSupply(tokenHash util.Uint160) (int64, error) { return c.nepTotalSupply(tokenHash) } -// NEP11BalanceOf invokes `balanceOf` NEP-11 method on a specified contract. +// NEP11BalanceOf invokes `balanceOf` NEP-11 method on the specified contract. func (c *Client) NEP11BalanceOf(tokenHash, owner util.Uint160) (int64, error) { return c.nepBalanceOf(tokenHash, owner, nil) } @@ -42,8 +42,8 @@ func (c *Client) NEP11TokenInfo(tokenHash util.Uint160) (*wallet.Token, error) { } // TransferNEP11 creates an invocation transaction that invokes 'transfer' method -// on a given token to move the whole NEP-11 token with the specified token ID to -// given account and sends it to the network returning just a hash of it. +// on the given token to move the whole NEP-11 token with the specified token ID to +// the given account and sends it to the network returning just a hash of it. func (c *Client) TransferNEP11(acc *wallet.Account, to util.Uint160, tokenHash util.Uint160, tokenID string, data interface{}, gas int64, cosigners []SignerAccount) (util.Uint256, error) { tx, err := c.CreateNEP11TransferTx(acc, tokenHash, gas, cosigners, to, tokenID, data) @@ -55,8 +55,8 @@ func (c *Client) TransferNEP11(acc *wallet.Account, to util.Uint160, } // CreateNEP11TransferTx creates an invocation transaction for the 'transfer' -// method of a given contract (token) to move the whole (or the specified amount -// of) NEP-11 token with the specified token ID to given account and returns it. +// method of the given contract (token) to move the whole (or the specified amount +// of) NEP-11 token with the specified token ID to the given account and returns it. // The returned transaction is not signed. CreateNEP11TransferTx is also a // helper for TransferNEP11 and TransferNEP11D. // `args` for TransferNEP11: to util.Uint160, tokenID string, data interface{}; @@ -111,8 +111,8 @@ func (c *Client) NEP11TokensOf(tokenHash util.Uint160, owner util.Uint160) ([][] // Non-divisible NFT methods section start. -// NEP11NDOwnerOf invokes `ownerOf` non-devisible NEP-11 method with the -// specified token ID on a specified contract. +// NEP11NDOwnerOf invokes `ownerOf` non-divisible NEP-11 method with the +// specified token ID on the specified contract. func (c *Client) NEP11NDOwnerOf(tokenHash util.Uint160, tokenID []byte) (util.Uint160, error) { result, err := c.InvokeFunction(tokenHash, "ownerOf", []smartcontract.Parameter{ { @@ -136,8 +136,8 @@ func (c *Client) NEP11NDOwnerOf(tokenHash util.Uint160, tokenID []byte) (util.Ui // Divisible NFT methods section start. // TransferNEP11D creates an invocation transaction that invokes 'transfer' -// method on a given token to move specified amount of divisible NEP-11 assets -// (in FixedN format using contract's number of decimals) to given account and +// method on the given token to move the specified amount of divisible NEP-11 assets +// (in FixedN format using contract's number of decimals) to the given account and // sends it to the network returning just a hash of it. func (c *Client) TransferNEP11D(acc *wallet.Account, to util.Uint160, tokenHash util.Uint160, amount int64, tokenID []byte, data interface{}, gas int64, cosigners []SignerAccount) (util.Uint256, error) { @@ -190,7 +190,7 @@ func (c *Client) NEP11DOwnerOf(tokenHash util.Uint160, tokenID []byte) ([]util.U // Optional NFT methods section start. -// NEP11Properties invokes `properties` optional NEP-11 method on a +// NEP11Properties invokes `properties` optional NEP-11 method on the // specified contract. func (c *Client) NEP11Properties(tokenHash util.Uint160, tokenID []byte) (*stackitem.Map, error) { result, err := c.InvokeFunction(tokenHash, "properties", []smartcontract.Parameter{{ diff --git a/pkg/rpc/client/nep17.go b/pkg/rpc/client/nep17.go index 22dcf6ea6..3f23a1378 100644 --- a/pkg/rpc/client/nep17.go +++ b/pkg/rpc/client/nep17.go @@ -29,22 +29,22 @@ type SignerAccount struct { Account *wallet.Account } -// NEP17Decimals invokes `decimals` NEP-17 method on a specified contract. +// NEP17Decimals invokes `decimals` NEP-17 method on the specified contract. func (c *Client) NEP17Decimals(tokenHash util.Uint160) (int64, error) { return c.nepDecimals(tokenHash) } -// NEP17Symbol invokes `symbol` NEP-17 method on a specified contract. +// NEP17Symbol invokes `symbol` NEP-17 method on the specified contract. func (c *Client) NEP17Symbol(tokenHash util.Uint160) (string, error) { return c.nepSymbol(tokenHash) } -// NEP17TotalSupply invokes `totalSupply` NEP-17 method on a specified contract. +// NEP17TotalSupply invokes `totalSupply` NEP-17 method on the specified contract. func (c *Client) NEP17TotalSupply(tokenHash util.Uint160) (int64, error) { return c.nepTotalSupply(tokenHash) } -// NEP17BalanceOf invokes `balanceOf` NEP-17 method on a specified contract. +// NEP17BalanceOf invokes `balanceOf` NEP-17 method on the specified contract. func (c *Client) NEP17BalanceOf(tokenHash, acc util.Uint160) (int64, error) { return c.nepBalanceOf(tokenHash, acc, nil) } @@ -55,8 +55,8 @@ func (c *Client) NEP17TokenInfo(tokenHash util.Uint160) (*wallet.Token, error) { } // CreateNEP17TransferTx creates an invocation transaction for the 'transfer' -// method of a given contract (token) to move specified amount of NEP-17 assets -// (in FixedN format using contract's number of decimals) to given account and +// method of the given contract (token) to move the specified amount of NEP-17 assets +// (in FixedN format using contract's number of decimals) to the given account and // returns it. The returned transaction is not signed. func (c *Client) CreateNEP17TransferTx(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64, data interface{}, cosigners []SignerAccount) (*transaction.Transaction, error) { @@ -71,7 +71,7 @@ func (c *Client) CreateNEP17TransferTx(acc *wallet.Account, to util.Uint160, // CreateNEP17MultiTransferTx creates an invocation transaction for performing // NEP-17 transfers from a single sender to multiple recipients with the given -// data and cosigners. Transaction's sender is included with the CalledByEntry +// data and cosigners. The transaction sender is included with the CalledByEntry // scope by default. func (c *Client) CreateNEP17MultiTransferTx(acc *wallet.Account, gas int64, recipients []TransferTarget, cosigners []SignerAccount) (*transaction.Transaction, error) { @@ -134,11 +134,11 @@ func (c *Client) CreateTxFromScript(script []byte, acc *wallet.Account, sysFee, } // TransferNEP17 creates an invocation transaction that invokes 'transfer' method -// on a given token to move specified amount of NEP-17 assets (in FixedN format -// using contract's number of decimals) to given account with data specified and +// on the given token to move the specified amount of NEP-17 assets (in FixedN format +// using contract's number of decimals) to the given account with the data specified and // sends it to the network returning just a hash of it. Cosigners argument // specifies a set of the transaction cosigners (may be nil or may include sender) -// with proper scope and accounts to cosign the transaction. If cosigning is +// with a proper scope and the accounts to cosign the transaction. If cosigning is // impossible (e.g. due to locked cosigner's account) an error is returned. func (c *Client) TransferNEP17(acc *wallet.Account, to util.Uint160, token util.Uint160, amount int64, gas int64, data interface{}, cosigners []SignerAccount) (util.Uint256, error) { diff --git a/pkg/rpc/client/nns/record.go b/pkg/rpc/client/nns/record.go index 8482e4ba9..e276b4836 100644 --- a/pkg/rpc/client/nns/record.go +++ b/pkg/rpc/client/nns/record.go @@ -1,6 +1,6 @@ package nns -// RecordState is a type that registered entities are saved to. +// RecordState is a type that registered entities are saved as. type RecordState struct { Name string Type RecordType @@ -10,7 +10,7 @@ type RecordState struct { // RecordType is domain name service record types. type RecordType byte -// Record types defined in [RFC 1035](https://tools.ietf.org/html/rfc1035) +// Record types are defined in [RFC 1035](https://tools.ietf.org/html/rfc1035) const ( // A represents address record type. A RecordType = 1 @@ -20,7 +20,7 @@ const ( TXT RecordType = 16 ) -// Record types defined in [RFC 3596](https://tools.ietf.org/html/rfc3596) +// Record types are defined in [RFC 3596](https://tools.ietf.org/html/rfc3596) const ( // AAAA represents IPv6 address record type. AAAA RecordType = 28 diff --git a/pkg/rpc/client/rpc.go b/pkg/rpc/client/rpc.go index 02648d1fb..835d9c5b3 100644 --- a/pkg/rpc/client/rpc.go +++ b/pkg/rpc/client/rpc.go @@ -29,7 +29,7 @@ import ( var errNetworkNotInitialized = errors.New("RPC client network is not initialized") -// CalculateNetworkFee calculates network fee for transaction. The transaction may +// CalculateNetworkFee calculates network fee for the transaction. The transaction may // have empty witnesses for contract signers and may have only verification scripts // filled for standard sig/multisig signers. func (c *Client) CalculateNetworkFee(tx *transaction.Transaction) (int64, error) { @@ -43,7 +43,7 @@ func (c *Client) CalculateNetworkFee(tx *transaction.Transaction) (int64, error) return resp.Value, nil } -// GetApplicationLog returns the contract log based on the specified txid. +// GetApplicationLog returns a contract log based on the specified txid. func (c *Client) GetApplicationLog(hash util.Uint256, trig *trigger.Type) (*result.ApplicationLog, error) { var ( params = request.NewRawParams(hash.StringLE()) @@ -58,7 +58,7 @@ func (c *Client) GetApplicationLog(hash util.Uint256, trig *trigger.Type) (*resu return resp, nil } -// GetBestBlockHash returns the hash of the tallest block in the main chain. +// GetBestBlockHash returns the hash of the tallest block in the blockchain. func (c *Client) GetBestBlockHash() (util.Uint256, error) { var resp = util.Uint256{} if err := c.performRequest("getbestblockhash", request.NewRawParams(), &resp); err != nil { @@ -67,7 +67,7 @@ func (c *Client) GetBestBlockHash() (util.Uint256, error) { return resp, nil } -// GetBlockCount returns the number of blocks in the main chain. +// GetBlockCount returns the number of blocks in the blockchain. func (c *Client) GetBlockCount() (uint32, error) { var resp uint32 if err := c.performRequest("getblockcount", request.NewRawParams(), &resp); err != nil { @@ -139,7 +139,7 @@ func (c *Client) getBlockVerbose(params request.RawParams) (*result.Block, error return resp, nil } -// GetBlockHash returns the hash value of the corresponding block, based on the specified index. +// GetBlockHash returns the hash value of the corresponding block based on the specified index. func (c *Client) GetBlockHash(index uint32) (util.Uint256, error) { var ( params = request.NewRawParams(index) @@ -151,9 +151,9 @@ func (c *Client) GetBlockHash(index uint32) (util.Uint256, error) { return resp, nil } -// GetBlockHeader returns the corresponding block header information from serialized hex string +// GetBlockHeader returns the corresponding block header information from a serialized hex string // according to the specified script hash. You should initialize network magic -// // with Init before calling GetBlockHeader. +// with Init before calling GetBlockHeader. func (c *Client) GetBlockHeader(hash util.Uint256) (*block.Header, error) { var ( params = request.NewRawParams(hash.StringLE()) @@ -186,7 +186,7 @@ func (c *Client) GetBlockHeaderCount() (uint32, error) { return resp, nil } -// GetBlockHeaderVerbose returns the corresponding block header information from Json format string +// GetBlockHeaderVerbose returns the corresponding block header information from a Json format string // according to the specified script hash. func (c *Client) GetBlockHeaderVerbose(hash util.Uint256) (*result.Header, error) { var ( @@ -199,7 +199,7 @@ func (c *Client) GetBlockHeaderVerbose(hash util.Uint256) (*result.Header, error return resp, nil } -// GetBlockSysFee returns the system fees of the block, based on the specified index. +// GetBlockSysFee returns the system fees of the block based on the specified index. func (c *Client) GetBlockSysFee(index uint32) (fixedn.Fixed8, error) { var ( params = request.NewRawParams(index) @@ -211,7 +211,7 @@ func (c *Client) GetBlockSysFee(index uint32) (fixedn.Fixed8, error) { return resp, nil } -// GetConnectionCount returns the current number of connections for the node. +// GetConnectionCount returns the current number of the connections for the node. func (c *Client) GetConnectionCount() (int, error) { var ( params = request.NewRawParams() @@ -223,7 +223,7 @@ func (c *Client) GetConnectionCount() (int, error) { return resp, nil } -// GetCommittee returns the current public keys of NEO nodes in committee. +// GetCommittee returns the current public keys of NEO nodes in the committee. func (c *Client) GetCommittee() (keys.PublicKeys, error) { var ( params = request.NewRawParams() @@ -235,17 +235,17 @@ func (c *Client) GetCommittee() (keys.PublicKeys, error) { return *resp, nil } -// GetContractStateByHash queries contract information, according to the contract script hash. +// GetContractStateByHash queries contract information according to the contract script hash. func (c *Client) GetContractStateByHash(hash util.Uint160) (*state.Contract, error) { return c.getContractState(hash.StringLE()) } -// GetContractStateByAddressOrName queries contract information, according to the contract address or name. +// GetContractStateByAddressOrName queries contract information according to the contract address or name. func (c *Client) GetContractStateByAddressOrName(addressOrName string) (*state.Contract, error) { return c.getContractState(addressOrName) } -// GetContractStateByID queries contract information, according to the contract ID. +// GetContractStateByID queries contract information according to the contract ID. func (c *Client) GetContractStateByID(id int32) (*state.Contract, error) { return c.getContractState(id) } @@ -303,10 +303,10 @@ func (c *Client) GetNEP17Balances(address util.Uint160) (*result.NEP17Balances, } // GetNEP11Properties is a wrapper for getnep11properties RPC. We recommend using -// NEP11Properties method instead of this to receive and work with proper VM types, -// this method is provided mostly for the sake of completeness. For well-known +// NEP11Properties method instead of this to receive proper VM types and work with them. +// This method is provided mostly for the sake of completeness. For well-known // attributes like "description", "image", "name" and "tokenURI" it returns strings, -// while for all other ones []byte (which can be nil). +// while for all others []byte (which can be nil). func (c *Client) GetNEP11Properties(asset util.Uint160, token []byte) (map[string]interface{}, error) { params := request.NewRawParams(asset.StringLE(), hex.EncodeToString(token)) resp := make(map[string]interface{}) @@ -334,7 +334,7 @@ func (c *Client) GetNEP11Properties(asset util.Uint160, token []byte) (map[strin } // GetNEP11Transfers is a wrapper for getnep11transfers RPC. Address parameter -// is mandatory, while all the others are optional. Limit and page parameters are +// is mandatory, while all others are optional. Limit and page parameters are // only supported by NeoGo servers and can only be specified with start and stop. func (c *Client) GetNEP11Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP11Transfers, error) { params, err := packTransfersParams(address, start, stop, limit, page) @@ -372,10 +372,10 @@ func packTransfersParams(address util.Uint160, start, stop *uint64, limit, page } // GetNEP17Transfers is a wrapper for getnep17transfers RPC. Address parameter -// is mandatory, while all the others are optional. Start and stop parameters +// is mandatory while all the others are optional. Start and stop parameters // are supported since neo-go 0.77.0 and limit and page since neo-go 0.78.0. -// These parameters are positional in the JSON-RPC call, you can't specify limit -// and not specify start/stop for example. +// These parameters are positional in the JSON-RPC call. For example, you can't specify the limit +// without specifying start/stop first. func (c *Client) GetNEP17Transfers(address util.Uint160, start, stop *uint64, limit, page *int) (*result.NEP17Transfers, error) { params, err := packTransfersParams(address, start, stop, limit, page) if err != nil { @@ -388,7 +388,7 @@ func (c *Client) GetNEP17Transfers(address util.Uint160, start, stop *uint64, li return resp, nil } -// GetPeers returns the list of nodes that the node is currently connected/disconnected from. +// GetPeers returns a list of the nodes that the node is currently connected to/disconnected from. func (c *Client) GetPeers() (*result.GetPeers, error) { var ( params = request.NewRawParams() @@ -400,7 +400,7 @@ func (c *Client) GetPeers() (*result.GetPeers, error) { return resp, nil } -// GetRawMemPool returns the list of unconfirmed transactions in memory. +// GetRawMemPool returns a list of unconfirmed transactions in the memory. func (c *Client) GetRawMemPool() ([]util.Uint256, error) { var ( params = request.NewRawParams() @@ -458,9 +458,9 @@ func (c *Client) GetState(stateroot util.Uint256, historicalContractHash util.Ui } // FindStates returns historical contract storage item states by the given stateroot, -// historical contract hash and historical prefix. If `start` path is specified, then items +// historical contract hash and historical prefix. If `start` path is specified, items // starting from `start` path are being returned (excluding item located at the start path). -// If `maxCount` specified, then maximum number of items to be returned equals to `maxCount`. +// If `maxCount` specified, the maximum number of items to be returned equals to `maxCount`. func (c *Client) FindStates(stateroot util.Uint256, historicalContractHash util.Uint160, historicalPrefix []byte, start []byte, maxCount *int) (result.FindStates, error) { if historicalPrefix == nil { @@ -485,12 +485,12 @@ func (c *Client) FindStates(stateroot util.Uint256, historicalContractHash util. return resp, nil } -// GetStateRootByHeight returns state root for the specified height. +// GetStateRootByHeight returns the state root for the specified height. func (c *Client) GetStateRootByHeight(height uint32) (*state.MPTRoot, error) { return c.getStateRoot(request.NewRawParams(height)) } -// GetStateRootByBlockHash returns state root for block with specified hash. +// GetStateRootByBlockHash returns the state root for the block with the specified hash. func (c *Client) GetStateRootByBlockHash(hash util.Uint256) (*state.MPTRoot, error) { return c.getStateRoot(request.NewRawParams(hash)) } @@ -503,7 +503,7 @@ func (c *Client) getStateRoot(params request.RawParams) (*state.MPTRoot, error) return resp, nil } -// GetStateHeight returns current validated and local node state height. +// GetStateHeight returns the current validated and local node state height. func (c *Client) GetStateHeight() (*result.StateHeight, error) { var ( params = request.NewRawParams() @@ -515,12 +515,12 @@ func (c *Client) GetStateHeight() (*result.StateHeight, error) { return resp, nil } -// GetStorageByID returns the stored value, according to the contract ID and the stored key. +// GetStorageByID returns the stored value according to the contract ID and the stored key. func (c *Client) GetStorageByID(id int32, key []byte) ([]byte, error) { return c.getStorage(request.NewRawParams(id, key)) } -// GetStorageByHash returns the stored value, according to the contract script hash and the stored key. +// GetStorageByHash returns the stored value according to the contract script hash and the stored key. func (c *Client) GetStorageByHash(hash util.Uint160, key []byte) ([]byte, error) { return c.getStorage(request.NewRawParams(hash.StringLE(), key)) } @@ -533,7 +533,7 @@ func (c *Client) getStorage(params request.RawParams) ([]byte, error) { return resp, nil } -// GetTransactionHeight returns the block index in which the transaction is found. +// GetTransactionHeight returns the block index where the transaction is found. func (c *Client) GetTransactionHeight(hash util.Uint256) (uint32, error) { var ( params = request.NewRawParams(hash.StringLE()) @@ -545,7 +545,7 @@ func (c *Client) GetTransactionHeight(hash util.Uint256) (uint32, error) { return resp, nil } -// GetUnclaimedGas returns unclaimed GAS amount for the specified address. +// GetUnclaimedGas returns the unclaimed GAS amount for the specified address. func (c *Client) GetUnclaimedGas(address string) (result.UnclaimedGas, error) { var ( params = request.NewRawParams(address) @@ -745,17 +745,17 @@ func (c *Client) SubmitBlock(b block.Block) (util.Uint256, error) { return resp.Hash, nil } -// SubmitRawOracleResponse submits raw oracle response to the oracle node. +// SubmitRawOracleResponse submits a raw oracle response to the oracle node. // Raw params are used to avoid excessive marshalling. func (c *Client) SubmitRawOracleResponse(ps request.RawParams) error { return c.performRequest("submitoracleresponse", ps, new(result.RelayResult)) } -// SignAndPushInvocationTx signs and pushes given script as an invocation -// transaction using given wif to sign it and given cosigners to cosign it if +// SignAndPushInvocationTx signs and pushes the given script as an invocation +// transaction using the given wif to sign it and the given cosigners to cosign it if // possible. It spends the amount of gas specified. It returns a hash of the // invocation transaction and an error. If one of the cosigners accounts is -// neither contract-based nor unlocked an error is returned. +// neither contract-based nor unlocked, an error is returned. func (c *Client) SignAndPushInvocationTx(script []byte, acc *wallet.Account, sysfee int64, netfee fixedn.Fixed8, cosigners []SignerAccount) (util.Uint256, error) { tx, err := c.CreateTxFromScript(script, acc, sysfee, int64(netfee), cosigners) if err != nil { @@ -764,9 +764,9 @@ func (c *Client) SignAndPushInvocationTx(script []byte, acc *wallet.Account, sys return c.SignAndPushTx(tx, acc, cosigners) } -// SignAndPushTx signs given transaction using given wif and cosigners and pushes +// SignAndPushTx signs the given transaction using the given wif and cosigners and pushes // it to the chain. It returns a hash of the transaction and an error. If one of -// the cosigners accounts is neither contract-based nor unlocked an error is +// the cosigners accounts is neither contract-based nor unlocked, an error is // returned. func (c *Client) SignAndPushTx(tx *transaction.Transaction, acc *wallet.Account, cosigners []SignerAccount) (util.Uint256, error) { var ( @@ -842,12 +842,12 @@ func getSigners(sender *wallet.Account, cosigners []SignerAccount) ([]transactio return signers, accounts, nil } -// SignAndPushP2PNotaryRequest creates and pushes P2PNotary request constructed from the main -// and fallback transactions using given wif to sign it. It returns the request and an error. +// SignAndPushP2PNotaryRequest creates and pushes a P2PNotary request constructed from the main +// and fallback transactions using the given wif to sign it. It returns the request and an error. // Fallback transaction is constructed from the given script using the amount of gas specified. // For successful fallback transaction validation at least 2*transaction.NotaryServiceFeePerKey -// GAS should be deposited to Notary contract. -// Main transaction should be constructed by the user. Several rules need to be met for +// GAS should be deposited to the Notary contract. +// Main transaction should be constructed by the user. Several rules should be met for // successful main transaction acceptance: // 1. Native Notary contract should be a signer of the main transaction. // 2. Notary signer should have None scope. @@ -1089,7 +1089,7 @@ func (c *Client) AddNetworkFee(tx *transaction.Transaction, extraFee int64, accs return nil } -// GetNetwork returns the network magic of the RPC node client connected to. +// GetNetwork returns the network magic of the RPC node the client connected to. func (c *Client) GetNetwork() (netmode.Magic, error) { c.cacheLock.RLock() defer c.cacheLock.RUnlock() @@ -1100,7 +1100,7 @@ func (c *Client) GetNetwork() (netmode.Magic, error) { return c.cache.network, nil } -// StateRootInHeader returns true if state root is contained in block header. +// StateRootInHeader returns true if the state root is contained in the block header. // You should initialize Client cache with Init() before calling StateRootInHeader. func (c *Client) StateRootInHeader() (bool, error) { c.cacheLock.RLock() diff --git a/pkg/rpc/client/rpc_test.go b/pkg/rpc/client/rpc_test.go index 1e58d2857..51f85ef46 100644 --- a/pkg/rpc/client/rpc_test.go +++ b/pkg/rpc/client/rpc_test.go @@ -109,7 +109,7 @@ func getTxMoveNeo() *result.TransactionOutputRaw { } // rpcClientTestCases contains `serverResponse` json data fetched from examples -// published in official C# JSON-RPC API v2.10.3 reference +// published in the official C# JSON-RPC API v2.10.3 reference // (see https://docs.neo.org/docs/en-us/reference/rpc/latest-version/api.html) var rpcClientTestCases = map[string][]rpcClientTestCase{ "getapplicationlog": { diff --git a/pkg/rpc/client/wsclient.go b/pkg/rpc/client/wsclient.go index 9c4ff5272..b67689852 100644 --- a/pkg/rpc/client/wsclient.go +++ b/pkg/rpc/client/wsclient.go @@ -21,17 +21,17 @@ import ( // WSClient is a websocket-enabled RPC client that can be used with appropriate // servers. It's supposed to be faster than Client because it has persistent -// connection to the server and at the same time is exposes some functionality +// connection to the server and at the same time it exposes some functionality // that is only provided via websockets (like event subscription mechanism). // WSClient is thread-safe and can be used from multiple goroutines to perform // RPC requests. type WSClient struct { Client // Notifications is a channel that is used to send events received from - // server. Client's code is supposed to be reading from this channel if - // it wants to use subscription mechanism, failing to do so will cause + // the server. Client's code is supposed to be reading from this channel if + // it wants to use subscription mechanism. Failing to do so will cause // WSClient to block even regular requests. This channel is not buffered. - // In case of protocol error or upon connection closure this channel will + // In case of protocol error or upon connection closure, this channel will // be closed, so make sure to handle this. Notifications chan Notification @@ -48,7 +48,7 @@ type WSClient struct { respChannels map[uint64]chan *response.Raw } -// Notification represents server-generated notification for client subscriptions. +// Notification represents a server-generated notification for client subscriptions. // Value can be one of block.Block, state.AppExecResult, subscriptions.NotificationEvent // transaction.Transaction or subscriptions.NotaryRequestEvent based on Type. type Notification struct { @@ -80,7 +80,7 @@ const ( // NewWS returns a new WSClient ready to use (with established websocket // connection). You need to use websocket URL for it like `ws://1.2.3.4/ws`. -// You should call Init method to initialize network magic the client is +// You should call Init method to initialize the network magic the client is // operating on. func NewWS(ctx context.Context, endpoint string, opts Options) (*WSClient, error) { dialer := websocket.Dialer{HandshakeTimeout: opts.DialTimeout} @@ -117,9 +117,9 @@ func NewWS(ctx context.Context, endpoint string, opts Options) (*WSClient, error // unusable. func (c *WSClient) Close() { if c.closeCalled.CAS(false, true) { - // Closing shutdown channel send signal to wsWriter to break out of the + // Closing shutdown channel sends a signal to wsWriter to break out of the // loop. In doing so it does ws.Close() closing the network connection - // which in turn makes wsReader receieve err from ws,ReadJSON() and also + // which in turn makes wsReader receive an err from ws.ReadJSON() and also // break out of the loop closing c.done channel in its shutdown sequence. close(c.shutdown) } @@ -156,7 +156,7 @@ readloop: case response.BlockEventID: sr, err := c.StateRootInHeader() if err != nil { - // Client is not initialised. + // Client is not initialized. break } val = block.New(sr) @@ -317,7 +317,7 @@ func (c *WSClient) performUnsubscription(id string) error { } // SubscribeForNewBlocks adds subscription for new block events to this instance -// of client. It can filtered by primary consensus node index, nil value doesn't +// of the client. It can be filtered by primary consensus node index, nil value doesn't // add any filters. func (c *WSClient) SubscribeForNewBlocks(primary *int) (string, error) { params := request.NewRawParams("block_added") @@ -328,7 +328,7 @@ func (c *WSClient) SubscribeForNewBlocks(primary *int) (string, error) { } // SubscribeForNewTransactions adds subscription for new transaction events to -// this instance of client. It can be filtered by sender and/or signer, nil +// this instance of the client. It can be filtered by the sender and/or the signer, nil // value is treated as missing filter. func (c *WSClient) SubscribeForNewTransactions(sender *util.Uint160, signer *util.Uint160) (string, error) { params := request.NewRawParams("transaction_added") @@ -339,8 +339,8 @@ func (c *WSClient) SubscribeForNewTransactions(sender *util.Uint160, signer *uti } // SubscribeForExecutionNotifications adds subscription for notifications -// generated during transaction execution to this instance of client. It can be -// filtered by contract's hash (that emits notifications), nil value puts no such +// generated during transaction execution to this instance of the client. It can be +// filtered by the contract's hash (that emits notifications), nil value puts no such // restrictions. func (c *WSClient) SubscribeForExecutionNotifications(contract *util.Uint160, name *string) (string, error) { params := request.NewRawParams("notification_from_execution") @@ -351,7 +351,7 @@ func (c *WSClient) SubscribeForExecutionNotifications(contract *util.Uint160, na } // SubscribeForTransactionExecutions adds subscription for application execution -// results generated during transaction execution to this instance of client. Can +// results generated during transaction execution to this instance of the client. It can // be filtered by state (HALT/FAULT) to check for successful or failing // transactions, nil value means no filtering. func (c *WSClient) SubscribeForTransactionExecutions(state *string) (string, error) { @@ -377,12 +377,12 @@ func (c *WSClient) SubscribeForNotaryRequests(sender *util.Uint160, mainSigner * return c.performSubscription(params) } -// Unsubscribe removes subscription for given event stream. +// Unsubscribe removes subscription for the given event stream. func (c *WSClient) Unsubscribe(id string) error { return c.performUnsubscription(id) } -// UnsubscribeAll removes all active subscriptions of current client. +// UnsubscribeAll removes all active subscriptions of the current client. func (c *WSClient) UnsubscribeAll() error { c.subscriptionsLock.Lock() defer c.subscriptionsLock.Unlock() diff --git a/pkg/rpc/client/wsclient_test.go b/pkg/rpc/client/wsclient_test.go index 531db6d5d..6e6ca2e1d 100644 --- a/pkg/rpc/client/wsclient_test.go +++ b/pkg/rpc/client/wsclient_test.go @@ -122,7 +122,7 @@ func TestWSClientUnsubscription(t *testing.T) { func TestWSClientEvents(t *testing.T) { var ok bool - // Events from RPC server test chain. + // Events from RPC server testchain. var events = []string{ `{"jsonrpc":"2.0","method":"transaction_executed","params":[{"container":"0xe1cd5e57e721d2a2e05fb1f08721b12057b25ab1dd7fd0f33ee1639932fdfad7","trigger":"Application","vmstate":"HALT","gasconsumed":"22910000","stack":[],"notifications":[{"contract":"0x1b4357bff5a01bdf2a6581247cf9ed1e24629176","eventname":"contract call","state":{"type":"Array","value":[{"type":"ByteString","value":"dHJhbnNmZXI="},{"type":"Array","value":[{"type":"ByteString","value":"dpFiJB7t+XwkgWUq3xug9b9XQxs="},{"type":"ByteString","value":"MW6FEDkBnTnfwsN9bD/uGf1YCYc="},{"type":"Integer","value":"1000"}]}]}},{"contract":"0x1b4357bff5a01bdf2a6581247cf9ed1e24629176","eventname":"transfer","state":{"type":"Array","value":[{"type":"ByteString","value":"dpFiJB7t+XwkgWUq3xug9b9XQxs="},{"type":"ByteString","value":"MW6FEDkBnTnfwsN9bD/uGf1YCYc="},{"type":"Integer","value":"1000"}]}}]}]}`, `{"jsonrpc":"2.0","method":"notification_from_execution","params":[{"container":"0xe1cd5e57e721d2a2e05fb1f08721b12057b25ab1dd7fd0f33ee1639932fdfad7","contract":"0x1b4357bff5a01bdf2a6581247cf9ed1e24629176","eventname":"contract call","state":{"type":"Array","value":[{"type":"ByteString","value":"dHJhbnNmZXI="},{"type":"Array","value":[{"type":"ByteString","value":"dpFiJB7t+XwkgWUq3xug9b9XQxs="},{"type":"ByteString","value":"MW6FEDkBnTnfwsN9bD/uGf1YCYc="},{"type":"Integer","value":"1000"}]}]}}]}`, diff --git a/pkg/rpc/request/param.go b/pkg/rpc/request/param.go index 79dc46aaa..2d21617a6 100644 --- a/pkg/rpc/request/param.go +++ b/pkg/rpc/request/param.go @@ -20,7 +20,7 @@ import ( type ( // Param represents a param either passed to - // the server or to send to a server using + // the server or to be sent to a server using // the client. Param struct { json.RawMessage @@ -33,18 +33,18 @@ type ( Type smartcontract.ParamType `json:"type"` Value Param `json:"value"` } - // BlockFilter is a wrapper structure for block event filter. The only + // BlockFilter is a wrapper structure for the block event filter. The only // allowed filter is primary index. BlockFilter struct { Primary int `json:"primary"` } - // TxFilter is a wrapper structure for transaction event filter. It + // TxFilter is a wrapper structure for the transaction event filter. It // allows to filter transactions by senders and signers. TxFilter struct { Sender *util.Uint160 `json:"sender,omitempty"` Signer *util.Uint160 `json:"signer,omitempty"` } - // NotificationFilter is a wrapper structure representing filter used for + // NotificationFilter is a wrapper structure representing a filter used for // notifications generated during transaction execution. Notifications can // be filtered by contract hash and by name. NotificationFilter struct { @@ -80,7 +80,7 @@ func (p Param) String() string { return str } -// GetStringStrict returns string value of the parameter. +// GetStringStrict returns a string value of the parameter. func (p *Param) GetStringStrict() (string, error) { if p == nil { return "", errMissingParameter @@ -102,7 +102,7 @@ func (p *Param) GetStringStrict() (string, error) { return "", errNotAString } -// GetString returns string value of the parameter or tries to cast parameter to a string value. +// GetString returns a string value of the parameter or tries to cast the parameter to a string value. func (p *Param) GetString() (string, error) { if p == nil { return "", errMissingParameter @@ -162,7 +162,7 @@ func (p *Param) GetBooleanStrict() (bool, error) { return false, errNotABool } -// GetBoolean returns boolean value of the parameter or tries to cast parameter to a bool value. +// GetBoolean returns a boolean value of the parameter or tries to cast the parameter to a bool value. func (p *Param) GetBoolean() (bool, error) { if p == nil { return false, errMissingParameter @@ -203,7 +203,7 @@ func (p *Param) GetBoolean() (bool, error) { } } -// GetIntStrict returns int value of the parameter if the parameter is integer. +// GetIntStrict returns an int value of the parameter if the parameter is an integer. func (p *Param) GetIntStrict() (int, error) { if p == nil { return 0, errMissingParameter @@ -251,7 +251,7 @@ func (p *Param) fillIntCache() (interface{}, error) { return nil, errNotAnInt } -// GetInt returns int value of the parameter or tries to cast parameter to an int value. +// GetInt returns an int value of the parameter or tries to cast the parameter to an int value. func (p *Param) GetInt() (int, error) { if p == nil { return 0, errMissingParameter @@ -281,7 +281,7 @@ func (p *Param) GetInt() (int, error) { } } -// GetBigInt returns big-interer value of the parameter. +// GetBigInt returns a big-integer value of the parameter. func (p *Param) GetBigInt() (*big.Int, error) { if p == nil { return nil, errMissingParameter @@ -334,7 +334,7 @@ func (p *Param) GetArray() ([]Param, error) { return nil, errNotAnArray } -// GetUint256 returns Uint256 value of the parameter. +// GetUint256 returns a Uint256 value of the parameter. func (p *Param) GetUint256() (util.Uint256, error) { s, err := p.GetString() if err != nil { @@ -344,7 +344,7 @@ func (p *Param) GetUint256() (util.Uint256, error) { return util.Uint256DecodeStringLE(strings.TrimPrefix(s, "0x")) } -// GetUint160FromHex returns Uint160 value of the parameter encoded in hex. +// GetUint160FromHex returns a Uint160 value of the parameter encoded in hex. func (p *Param) GetUint160FromHex() (util.Uint160, error) { s, err := p.GetString() if err != nil { @@ -354,7 +354,7 @@ func (p *Param) GetUint160FromHex() (util.Uint160, error) { return util.Uint160DecodeStringLE(strings.TrimPrefix(s, "0x")) } -// GetUint160FromAddress returns Uint160 value of the parameter that was +// GetUint160FromAddress returns a Uint160 value of the parameter that was // supplied as an address. func (p *Param) GetUint160FromAddress() (util.Uint160, error) { s, err := p.GetString() @@ -365,7 +365,7 @@ func (p *Param) GetUint160FromAddress() (util.Uint160, error) { return address.StringToUint160(s) } -// GetUint160FromAddressOrHex returns Uint160 value of the parameter that was +// GetUint160FromAddressOrHex returns a Uint160 value of the parameter that was // supplied either as raw hex or as an address. func (p *Param) GetUint160FromAddressOrHex() (util.Uint160, error) { u, err := p.GetUint160FromHex() @@ -375,7 +375,7 @@ func (p *Param) GetUint160FromAddressOrHex() (util.Uint160, error) { return p.GetUint160FromAddress() } -// GetFuncParam returns current parameter as a function call parameter. +// GetFuncParam returns the current parameter as a function call parameter. func (p *Param) GetFuncParam() (FuncParam, error) { if p == nil { return FuncParam{}, errMissingParameter @@ -386,7 +386,7 @@ func (p *Param) GetFuncParam() (FuncParam, error) { return fp, err } -// GetBytesHex returns []byte value of the parameter if +// GetBytesHex returns a []byte value of the parameter if // it is a hex-encoded string. func (p *Param) GetBytesHex() ([]byte, error) { s, err := p.GetString() @@ -397,7 +397,7 @@ func (p *Param) GetBytesHex() ([]byte, error) { return hex.DecodeString(s) } -// GetBytesBase64 returns []byte value of the parameter if +// GetBytesBase64 returns a []byte value of the parameter if // it is a base64-encoded string. func (p *Param) GetBytesBase64() ([]byte, error) { s, err := p.GetString() @@ -408,7 +408,7 @@ func (p *Param) GetBytesBase64() ([]byte, error) { return base64.StdEncoding.DecodeString(s) } -// GetSignerWithWitness returns SignerWithWitness value of the parameter. +// GetSignerWithWitness returns a SignerWithWitness value of the parameter. func (p *Param) GetSignerWithWitness() (SignerWithWitness, error) { // This one doesn't need to be cached, it's used only once. aux := new(signerWithWitnessAux) @@ -440,7 +440,7 @@ func (p *Param) GetSignerWithWitness() (SignerWithWitness, error) { } // GetSignersWithWitnesses returns a slice of SignerWithWitness with CalledByEntry -// scope from array of Uint160 or array of serialized transaction.Signer stored +// scope from an array of Uint160 or an array of serialized transaction.Signer stored // in the parameter. func (p Param) GetSignersWithWitnesses() ([]transaction.Signer, []transaction.Witness, error) { hashes, err := p.GetArray() @@ -474,12 +474,12 @@ func (p Param) GetSignersWithWitnesses() ([]transaction.Signer, []transaction.Wi return signers, witnesses, nil } -// IsNull returns whether parameter represents JSON nil value. +// IsNull returns whether the parameter represents JSON nil value. func (p *Param) IsNull() bool { return bytes.Equal(p.RawMessage, jsonNullBytes) } -// signerWithWitnessAux is an auxiluary struct for JSON marshalling. We need it because of +// signerWithWitnessAux is an auxiliary struct for JSON marshalling. We need it because of // DisallowUnknownFields JSON marshaller setting. type signerWithWitnessAux struct { Account string `json:"account"` @@ -491,7 +491,7 @@ type signerWithWitnessAux struct { VerificationScript []byte `json:"verification,omitempty"` } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (s *SignerWithWitness) MarshalJSON() ([]byte, error) { signer := &signerWithWitnessAux{ Account: s.Account.StringLE(), diff --git a/pkg/rpc/request/txBuilder.go b/pkg/rpc/request/txBuilder.go index e98afec8f..563abba7b 100644 --- a/pkg/rpc/request/txBuilder.go +++ b/pkg/rpc/request/txBuilder.go @@ -14,7 +14,7 @@ import ( ) // ExpandArrayIntoScript pushes all FuncParam parameters from the given array -// into the given buffer in reverse order. +// into the given buffer in the reverse order. func ExpandArrayIntoScript(script *io.BinWriter, slice []Param) error { for j := len(slice) - 1; j >= 0; j-- { fp, err := slice[j].GetFuncParam() @@ -100,8 +100,8 @@ func ExpandArrayIntoScript(script *io.BinWriter, slice []Param) error { return script.Err } -// CreateFunctionInvocationScript creates a script to invoke given contract with -// given parameters. +// CreateFunctionInvocationScript creates a script to invoke the given contract with +// the given parameters. func CreateFunctionInvocationScript(contract util.Uint160, method string, param *Param) ([]byte, error) { script := io.NewBufBinWriter() if param == nil { diff --git a/pkg/rpc/request/types.go b/pkg/rpc/request/types.go index 2281ef3ae..1862649d1 100644 --- a/pkg/rpc/request/types.go +++ b/pkg/rpc/request/types.go @@ -12,12 +12,12 @@ const ( // JSONRPCVersion is the only JSON-RPC protocol version supported. JSONRPCVersion = "2.0" - // maxBatchSize is the maximum number of request per batch. + // maxBatchSize is the maximum number of requests per batch. maxBatchSize = 100 ) // RawParams is just a slice of abstract values, used to represent parameters -// passed from client to server. +// passed from the client to the server. type RawParams struct { Values []interface{} } @@ -61,7 +61,7 @@ type In struct { // batch: https://www.jsonrpc.org/specification#batch. type Batch []In -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (r Request) MarshalJSON() ([]byte, error) { if r.In != nil { return json.Marshal(r.In) @@ -69,7 +69,7 @@ func (r Request) MarshalJSON() ([]byte, error) { return json.Marshal(r.Batch) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (r *Request) UnmarshalJSON(data []byte) error { var ( in *In diff --git a/pkg/rpc/response/errors.go b/pkg/rpc/response/errors.go index de0bf4057..e31c31c5e 100644 --- a/pkg/rpc/response/errors.go +++ b/pkg/rpc/response/errors.go @@ -96,7 +96,7 @@ func (e *Error) Error() string { return fmt.Sprintf("%s (%d) - %s - %s", e.Message, e.Code, e.Data, e.Cause) } -// WrapErrorWithData returns copy of the given error with specified data and cause. +// WrapErrorWithData returns copy of the given error with the specified data and cause. // It does not modify the source error. func WrapErrorWithData(e *Error, data error) *Error { return NewError(e.Code, e.HTTPCode, e.Message, data.Error(), data) diff --git a/pkg/rpc/response/events.go b/pkg/rpc/response/events.go index e7e676eaa..15264e041 100644 --- a/pkg/rpc/response/events.go +++ b/pkg/rpc/response/events.go @@ -14,13 +14,13 @@ const ( InvalidEventID EventID = iota // BlockEventID is a `block_added` event. BlockEventID - // TransactionEventID corresponds to `transaction_added` event. + // TransactionEventID corresponds to the `transaction_added` event. TransactionEventID // NotificationEventID represents `notification_from_execution` events. NotificationEventID // ExecutionEventID is used for `transaction_executed` events. ExecutionEventID - // NotaryRequestEventID is used for `notary_request_event` event. + // NotaryRequestEventID is used for the `notary_request_event` event. NotaryRequestEventID // MissedEventID notifies user of missed events. MissedEventID EventID = 255 @@ -46,7 +46,7 @@ func (e EventID) String() string { } } -// GetEventIDFromString converts input string into an EventID if it's possible. +// GetEventIDFromString converts an input string into an EventID if it's possible. func GetEventIDFromString(s string) (EventID, error) { switch s { case "block_added": @@ -66,12 +66,12 @@ func GetEventIDFromString(s string) (EventID, error) { } } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (e EventID) MarshalJSON() ([]byte, error) { return json.Marshal(e.String()) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (e *EventID) UnmarshalJSON(b []byte) error { var s string diff --git a/pkg/rpc/response/result/application_log.go b/pkg/rpc/response/result/application_log.go index 98920e720..74f9b324a 100644 --- a/pkg/rpc/response/result/application_log.go +++ b/pkg/rpc/response/result/application_log.go @@ -10,7 +10,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// ApplicationLog represent the results of the script executions for block or transaction. +// ApplicationLog represent the results of the script executions for a block or a transaction. type ApplicationLog struct { Container util.Uint256 IsTransaction bool @@ -24,7 +24,7 @@ type applicationLogAux struct { Executions []json.RawMessage `json:"executions"` } -// MarshalJSON implements implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (l ApplicationLog) MarshalJSON() ([]byte, error) { result := &applicationLogAux{ Executions: make([]json.RawMessage, len(l.Executions)), @@ -44,7 +44,7 @@ func (l ApplicationLog) MarshalJSON() ([]byte, error) { return json.Marshal(result) } -// UnmarshalJSON implements implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (l *ApplicationLog) UnmarshalJSON(data []byte) error { aux := new(applicationLogAux) if err := json.Unmarshal(data, aux); err != nil { @@ -68,7 +68,7 @@ func (l *ApplicationLog) UnmarshalJSON(data []byte) error { return nil } -// NewApplicationLog creates ApplicationLog from a set of several application execution results +// NewApplicationLog creates an ApplicationLog from a set of several application execution results // including only the results with the specified trigger. func NewApplicationLog(hash util.Uint256, aers []state.AppExecResult, trig trigger.Type) ApplicationLog { result := ApplicationLog{ diff --git a/pkg/rpc/response/result/block.go b/pkg/rpc/response/result/block.go index 418067a7b..96394776f 100644 --- a/pkg/rpc/response/result/block.go +++ b/pkg/rpc/response/result/block.go @@ -22,7 +22,7 @@ type ( BlockMetadata } - // BlockMetadata is an additional metadata added to standard + // BlockMetadata is an additional metadata added to the standard // block.Block. BlockMetadata struct { Size int `json:"size"` @@ -49,7 +49,7 @@ func NewBlock(b *block.Block, chain LedgerAux) Block { return res } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (b Block) MarshalJSON() ([]byte, error) { output, err := json.Marshal(b.BlockMetadata) if err != nil { @@ -62,7 +62,7 @@ func (b Block) MarshalJSON() ([]byte, error) { // We have to keep both "fields" at the same level in json in order to // match C# API, so there's no way to marshall Block correctly with - // standard json.Marshaller tool. + // the standard json.Marshaller tool. if output[len(output)-1] != '}' || baseBytes[0] != '{' { return nil, errors.New("can't merge internal jsons") } @@ -71,7 +71,7 @@ func (b Block) MarshalJSON() ([]byte, error) { return output, nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (b *Block) UnmarshalJSON(data []byte) error { // As block.Block and BlockMetadata are at the same level in json, // do unmarshalling separately for both structs. diff --git a/pkg/rpc/response/result/block_header.go b/pkg/rpc/response/result/block_header.go index 2c3bd8ae8..1c23e51c7 100644 --- a/pkg/rpc/response/result/block_header.go +++ b/pkg/rpc/response/result/block_header.go @@ -10,8 +10,8 @@ import ( ) type ( - // Header wrapper used for the representation of - // block header on the RPC Server. + // Header wrapper used for a representation of + // the block header on the RPC Server. Header struct { block.Header BlockMetadata @@ -35,7 +35,7 @@ func NewHeader(h *block.Header, chain LedgerAux) Header { return res } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (h Header) MarshalJSON() ([]byte, error) { output, err := json.Marshal(h.BlockMetadata) if err != nil { @@ -57,7 +57,7 @@ func (h Header) MarshalJSON() ([]byte, error) { return output, nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (h *Header) UnmarshalJSON(data []byte) error { // As block.Block and BlockMetadata are at the same level in json, // do unmarshalling separately for both structs. diff --git a/pkg/rpc/response/result/invoke.go b/pkg/rpc/response/result/invoke.go index 1d24914c2..ea9edaffc 100644 --- a/pkg/rpc/response/result/invoke.go +++ b/pkg/rpc/response/result/invoke.go @@ -13,7 +13,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// Invoke represents code invocation result and is used by several RPC calls +// Invoke represents a code invocation result and is used by several RPC calls // that invoke functions, scripts and generic bytecode. type Invoke struct { State string @@ -34,7 +34,7 @@ type InvokeDiag struct { Invocations []*vm.InvocationTree `json:"invokedcontracts"` } -// NewInvoke returns new Invoke structure with the given fields set. +// NewInvoke returns a new Invoke structure with the given fields set. func NewInvoke(ic *interop.Context, script []byte, faultException string, maxIteratorResultItems int) *Invoke { var diag *InvokeDiag tree := ic.VM.GetInvocationTree() @@ -78,7 +78,7 @@ type iteratorAux struct { Truncated bool `json:"truncated"` } -// Iterator represents deserialized VM iterator values with truncated flag. +// Iterator represents deserialized VM iterator values with a truncated flag. type Iterator struct { Values []stackitem.Item Truncated bool @@ -92,7 +92,7 @@ func (r *Invoke) Finalize() { } } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (r Invoke) MarshalJSON() ([]byte, error) { defer r.Finalize() var st json.RawMessage @@ -153,7 +153,7 @@ func (r Invoke) MarshalJSON() ([]byte, error) { }) } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (r *Invoke) UnmarshalJSON(data []byte) error { var err error aux := new(invokeAux) diff --git a/pkg/rpc/response/result/mpt.go b/pkg/rpc/response/result/mpt.go index 8ba54defb..ff2a6b1a4 100644 --- a/pkg/rpc/response/result/mpt.go +++ b/pkg/rpc/response/result/mpt.go @@ -14,7 +14,7 @@ type StateHeight struct { Validated uint32 `json:"validatedrootindex"` } -// ProofWithKey represens key-proof pair. +// ProofWithKey represens a key-proof pair. type ProofWithKey struct { Key []byte Proof [][]byte @@ -26,7 +26,7 @@ type VerifyProof struct { Value []byte } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (p *ProofWithKey) MarshalJSON() ([]byte, error) { w := io.NewBufBinWriter() p.EncodeBinary(w.BinWriter) @@ -54,7 +54,7 @@ func (p *ProofWithKey) DecodeBinary(r *io.BinReader) { } } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (p *ProofWithKey) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { @@ -81,7 +81,7 @@ func (p *ProofWithKey) FromString(s string) error { return r.Err } -// MarshalJSON implements json.Marshaler. +// MarshalJSON implements the json.Marshaler. func (p *VerifyProof) MarshalJSON() ([]byte, error) { if p.Value == nil { return []byte(`"invalid"`), nil @@ -89,7 +89,7 @@ func (p *VerifyProof) MarshalJSON() ([]byte, error) { return []byte(`"` + base64.StdEncoding.EncodeToString(p.Value) + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler. +// UnmarshalJSON implements the json.Unmarshaler. func (p *VerifyProof) UnmarshalJSON(data []byte) error { if bytes.Equal(data, []byte(`"invalid"`)) { p.Value = nil diff --git a/pkg/rpc/response/result/peers.go b/pkg/rpc/response/result/peers.go index b18acc0e8..4a4c4f923 100644 --- a/pkg/rpc/response/result/peers.go +++ b/pkg/rpc/response/result/peers.go @@ -12,10 +12,10 @@ type ( Bad Peers `json:"bad"` } - // Peers represent a slice of peers. + // Peers represents a slice of peers. Peers []Peer - // Peer represents the peer. + // Peer represents a peer. Peer struct { Address string `json:"address"` Port string `json:"port"` diff --git a/pkg/rpc/response/result/subscriptions/notary_request_event.go b/pkg/rpc/response/result/subscriptions/notary_request_event.go index 2566bc623..f1cd35daa 100644 --- a/pkg/rpc/response/result/subscriptions/notary_request_event.go +++ b/pkg/rpc/response/result/subscriptions/notary_request_event.go @@ -5,8 +5,8 @@ import ( "github.com/nspcc-dev/neo-go/pkg/network/payload" ) -// NotaryRequestEvent represents P2PNotaryRequest event either added or removed -// from notary payload pool. +// NotaryRequestEvent represents a P2PNotaryRequest event either added or removed +// from the notary payload pool. type NotaryRequestEvent struct { Type mempoolevent.Type `json:"type"` NotaryRequest *payload.P2PNotaryRequest `json:"notaryrequest"` diff --git a/pkg/rpc/response/result/subscriptions/notification_event.go b/pkg/rpc/response/result/subscriptions/notification_event.go index 783e5ec9f..305375071 100644 --- a/pkg/rpc/response/result/subscriptions/notification_event.go +++ b/pkg/rpc/response/result/subscriptions/notification_event.go @@ -9,7 +9,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// NotificationEvent represents wrapper for notification from script execution. +// NotificationEvent represents a wrapper for a notification from script execution. type NotificationEvent struct { // Container hash is the hash of script container which is either a block or a transaction. Container util.Uint256 @@ -21,7 +21,7 @@ type notificationEventAux struct { Container util.Uint256 `json:"container"` } -// MarshalJSON implements implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (ne *NotificationEvent) MarshalJSON() ([]byte, error) { h, err := json.Marshal(¬ificationEventAux{ Container: ne.Container, @@ -42,7 +42,7 @@ func (ne *NotificationEvent) MarshalJSON() ([]byte, error) { return h, nil } -// UnmarshalJSON implements implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (ne *NotificationEvent) UnmarshalJSON(data []byte) error { aux := new(notificationEventAux) if err := json.Unmarshal(data, aux); err != nil { diff --git a/pkg/rpc/response/result/tx_raw_output.go b/pkg/rpc/response/result/tx_raw_output.go index f2e74bbee..326923c8a 100644 --- a/pkg/rpc/response/result/tx_raw_output.go +++ b/pkg/rpc/response/result/tx_raw_output.go @@ -44,7 +44,7 @@ func NewTransactionOutputRaw(tx *transaction.Transaction, header *block.Header, return result } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (t TransactionOutputRaw) MarshalJSON() ([]byte, error) { output, err := json.Marshal(t.TransactionMetadata) if err != nil { @@ -65,7 +65,7 @@ func (t TransactionOutputRaw) MarshalJSON() ([]byte, error) { return output, nil } -// UnmarshalJSON implements json.Marshaler interface. +// UnmarshalJSON implements the json.Marshaler interface. func (t *TransactionOutputRaw) UnmarshalJSON(data []byte) error { // As transaction.Transaction and tranactionOutputRaw are at the same level in json, // do unmarshalling separately for both structs. diff --git a/pkg/rpc/response/result/unclaimed_gas.go b/pkg/rpc/response/result/unclaimed_gas.go index ae62b4124..fc1bdf581 100644 --- a/pkg/rpc/response/result/unclaimed_gas.go +++ b/pkg/rpc/response/result/unclaimed_gas.go @@ -15,13 +15,13 @@ type UnclaimedGas struct { Unclaimed big.Int } -// unclaimedGas is an auxiliary struct for JSON marhsalling. +// unclaimedGas is an auxiliary struct for JSON marshalling. type unclaimedGas struct { Address string `json:"address"` Unclaimed string `json:"unclaimed"` } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (g UnclaimedGas) MarshalJSON() ([]byte, error) { gas := &unclaimedGas{ Address: address.Uint160ToString(g.Address), @@ -30,7 +30,7 @@ func (g UnclaimedGas) MarshalJSON() ([]byte, error) { return json.Marshal(gas) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (g *UnclaimedGas) UnmarshalJSON(data []byte) error { gas := new(unclaimedGas) if err := json.Unmarshal(data, gas); err != nil { diff --git a/pkg/rpc/response/result/validate_address.go b/pkg/rpc/response/result/validate_address.go index bb4963893..12c092afc 100644 --- a/pkg/rpc/response/result/validate_address.go +++ b/pkg/rpc/response/result/validate_address.go @@ -1,8 +1,8 @@ package result -// ValidateAddress represents result of the `validateaddress` call. Notice that -// Address is an interface{} here because server echoes back whatever address -// value user has sent to it, even if it's not a string. +// ValidateAddress represents a result of the `validateaddress` call. Notice that +// Address is an interface{} here because the server echoes back whatever address +// value a user has sent to it, even if it's not a string. type ValidateAddress struct { Address interface{} `json:"address"` IsValid bool `json:"isvalid"` diff --git a/pkg/rpc/response/result/version.go b/pkg/rpc/response/result/version.go index b2823a810..16018b647 100644 --- a/pkg/rpc/response/result/version.go +++ b/pkg/rpc/response/result/version.go @@ -23,7 +23,7 @@ type ( Nonce uint32 UserAgent string Protocol Protocol - // StateRootInHeader is true if state root is contained in block header. + // StateRootInHeader is true if state root is contained in the block header. // Deprecated: use Protocol.StateRootInHeader instead StateRootInHeader bool } diff --git a/pkg/rpc/rpc_config.go b/pkg/rpc/rpc_config.go index cc0cdee9b..97890c058 100644 --- a/pkg/rpc/rpc_config.go +++ b/pkg/rpc/rpc_config.go @@ -10,8 +10,8 @@ type ( Address string `yaml:"Address"` Enabled bool `yaml:"Enabled"` EnableCORSWorkaround bool `yaml:"EnableCORSWorkaround"` - // MaxGasInvoke is a maximum amount of gas which - // can be spent during RPC call. + // MaxGasInvoke is the maximum amount of GAS which + // can be spent during an RPC call. MaxGasInvoke fixedn.Fixed8 `yaml:"MaxGasInvoke"` MaxIteratorResultItems int `yaml:"MaxIteratorResultItems"` MaxFindResultItems int `yaml:"MaxFindResultItems"` diff --git a/pkg/rpc/server/server.go b/pkg/rpc/server/server.go index e370fb8f4..a60feace1 100644 --- a/pkg/rpc/server/server.go +++ b/pkg/rpc/server/server.go @@ -87,7 +87,7 @@ type ( ) const ( - // Message limit for receiving side. + // Message limit for a receiving side. wsReadLimit = 4096 // Disconnection timeout. @@ -100,7 +100,7 @@ const ( wsWriteLimit = wsPingPeriod / 2 // Maximum number of subscribers per Server. Each websocket client is - // treated like subscriber, so technically it's a limit on websocket + // treated like a subscriber, so technically it's a limit on websocket // connections. maxSubscribers = 64 @@ -987,17 +987,17 @@ func (s *Server) getTokenTransfers(ps request.Params, isNEP11 bool) (interface{} } cache := make(map[int32]util.Uint160) var resCount, frameCount int - // handleTransfer returns items to be added into received and sent arrays + // handleTransfer returns items to be added into the received and sent arrays // along with a continue flag and error. var handleTransfer = func(tr *state.NEP17Transfer) (*result.NEP17Transfer, *result.NEP17Transfer, bool, error) { var received, sent *result.NEP17Transfer - // Iterating from newest to oldest, not yet reached required + // Iterating from the newest to the oldest, not yet reached required // time frame, continue looping. if tr.Timestamp > end { return nil, nil, true, nil } - // Iterating from newest to oldest, moved past required + // Iterating from the newest to the oldest, moved past required // time frame, stop looping. if tr.Timestamp < start { return nil, nil, false, nil @@ -1804,8 +1804,8 @@ func (s *Server) getFakeNextBlock(nextBlockHeight uint32) (*block.Block, error) return b, nil } -// runScriptInVM runs given script in a new test VM and returns the invocation -// result. The script is either a simple script in case of `application` trigger +// runScriptInVM runs the given script in a new test VM and returns the invocation +// result. The script is either a simple script in case of `application` trigger, // witness invocation script in case of `verification` trigger (it pushes `verify` // arguments on stack before verification). In case of contract verification // contractScriptHash should be specified. diff --git a/pkg/rpc/server/subscription.go b/pkg/rpc/server/subscription.go index 05068b375..ef9d6ea66 100644 --- a/pkg/rpc/server/subscription.go +++ b/pkg/rpc/server/subscription.go @@ -19,7 +19,7 @@ type ( overflown atomic.Bool // These work like slots as there is not a lot of them (it's // cheaper doing it this way rather than creating a map), - // pointing to EventID is an obvious overkill at the moment, but + // pointing to an EventID is an obvious overkill at the moment, but // that's not for long. feeds [maxFeeds]feed } @@ -33,13 +33,13 @@ const ( // Maximum number of subscriptions per one client. maxFeeds = 16 - // This sets notification messages buffer depth, it may seem to be quite + // This sets notification messages buffer depth. It may seem to be quite // big, but there is a big gap in speed between internal event processing // and networking communication that is combined with spiky nature of our // event generation process, which leads to lots of events generated in - // short time and they will put some pressure to this buffer (consider + // a short time and they will put some pressure to this buffer (consider // ~500 invocation txs in one block with some notifications). At the same - // time this channel is about sending pointers, so it's doesn't cost + // time, this channel is about sending pointers, so it's doesn't cost // a lot in terms of memory used. notificationBufSize = 1024 ) diff --git a/pkg/rpc/server/tokens.go b/pkg/rpc/server/tokens.go index 608c0b818..9cfd5cd7a 100644 --- a/pkg/rpc/server/tokens.go +++ b/pkg/rpc/server/tokens.go @@ -11,7 +11,7 @@ type tokenTransfers struct { Address string `json:"address"` } -// nep17TransferToNEP11 adds an ID to provided NEP-17 transfer and returns a new +// nep17TransferToNEP11 adds an ID to the provided NEP-17 transfer and returns a new // NEP-11 structure. func nep17TransferToNEP11(t17 *result.NEP17Transfer, id string) result.NEP11Transfer { return result.NEP11Transfer{ diff --git a/pkg/services/helpers/rpcbroadcaster/broadcaster.go b/pkg/services/helpers/rpcbroadcaster/broadcaster.go index d1126cfc7..b43225325 100644 --- a/pkg/services/helpers/rpcbroadcaster/broadcaster.go +++ b/pkg/services/helpers/rpcbroadcaster/broadcaster.go @@ -7,7 +7,7 @@ import ( "go.uber.org/zap" ) -// RPCBroadcaster represent generic RPC broadcaster. +// RPCBroadcaster represents a generic RPC broadcaster. type RPCBroadcaster struct { Clients map[string]*RPCClient Log *zap.Logger @@ -17,7 +17,7 @@ type RPCBroadcaster struct { sendTimeout time.Duration } -// NewRPCBroadcaster returns new RPC broadcaster instance. +// NewRPCBroadcaster returns a new RPC broadcaster instance. func NewRPCBroadcaster(log *zap.Logger, sendTimeout time.Duration) *RPCBroadcaster { return &RPCBroadcaster{ Clients: make(map[string]*RPCClient), diff --git a/pkg/services/helpers/rpcbroadcaster/client.go b/pkg/services/helpers/rpcbroadcaster/client.go index 6dce47492..403c726ea 100644 --- a/pkg/services/helpers/rpcbroadcaster/client.go +++ b/pkg/services/helpers/rpcbroadcaster/client.go @@ -9,7 +9,7 @@ import ( "go.uber.org/zap" ) -// RPCClient represent rpc client for a single node. +// RPCClient represent an rpc client for a single node. type RPCClient struct { client *client.Client addr string @@ -20,10 +20,10 @@ type RPCClient struct { method SendMethod } -// SendMethod represents rpc method for sending data to other nodes. +// SendMethod represents an rpc method for sending data to other nodes. type SendMethod func(*client.Client, request.RawParams) error -// NewRPCClient returns new rpc client for provided address and method. +// NewRPCClient returns a new rpc client for the provided address and method. func (r *RPCBroadcaster) NewRPCClient(addr string, method SendMethod, timeout time.Duration, ch chan request.RawParams) *RPCClient { return &RPCClient{ addr: addr, diff --git a/pkg/services/notary/notary.go b/pkg/services/notary/notary.go index 66dd24e78..e79f72439 100644 --- a/pkg/services/notary/notary.go +++ b/pkg/services/notary/notary.go @@ -36,7 +36,7 @@ type ( VerifyWitness(util.Uint160, hash.Hashable, *transaction.Witness, int64) (int64, error) } - // Notary represents Notary module. + // Notary represents a Notary module. Notary struct { Config Config @@ -45,12 +45,12 @@ type ( // onTransaction is a callback for completed transactions (mains or fallbacks) sending. onTransaction func(tx *transaction.Transaction) error // newTxs is a channel where new transactions are sent - // to be processed in a `onTransaction` callback. + // to be processed in an `onTransaction` callback. newTxs chan txHashPair // reqMtx protects requests list. reqMtx sync.RWMutex - // requests represents the map of main transactions which needs to be completed + // requests represents a map of main transactions which needs to be completed // with the associated fallback transactions grouped by the main transaction hash requests map[util.Uint256]*request @@ -79,21 +79,21 @@ const defaultTxChannelCapacity = 100 type ( // request represents Notary service request. request struct { - // isSent indicates whether main transaction was successfully sent to the network. + // isSent indicates whether the main transaction was successfully sent to the network. isSent bool main *transaction.Transaction // minNotValidBefore is the minimum NVB value among fallbacks transactions. - // We stop trying to send mainTx to the network if the chain reaches minNotValidBefore height. + // We stop trying to send the mainTx to the network if the chain reaches the minNotValidBefore height. minNotValidBefore uint32 fallbacks []*transaction.Transaction witnessInfo []witnessInfo } - // witnessInfo represents information about signer and its witness. + // witnessInfo represents information about the signer and its witness. witnessInfo struct { typ RequestType - // nSigsLeft is the number of signatures left to collect to complete main transaction. + // nSigsLeft is the number of signatures left to collect to complete the main transaction. // Initial nSigsLeft value is defined as following: // nSigsLeft == nKeys for standard signature request; // nSigsLeft <= nKeys for multisignature request; @@ -119,7 +119,7 @@ func (r request) isMainCompleted() bool { return true } -// NewNotary returns new Notary module. +// NewNotary returns a new Notary module. func NewNotary(cfg Config, net netmode.Magic, mp *mempool.Pool, onTransaction func(tx *transaction.Transaction) error) (*Notary, error) { w := cfg.MainCfg.UnlockWallet wallet, err := wallet.NewWalletFromFile(w.Path) @@ -157,7 +157,7 @@ func (n *Notary) Name() string { return "notary" } -// Start runs Notary module in a separate goroutine. +// Start runs a Notary module in a separate goroutine. func (n *Notary) Start() { n.Config.Log.Info("starting notary service") n.Config.Chain.SubscribeForBlocks(n.blocksCh) @@ -183,18 +183,18 @@ func (n *Notary) mainLoop() { } } case <-n.blocksCh: - // new block was added, need to check for valid fallbacks + // a new block was added, we need to check for valid fallbacks n.PostPersist() } } } -// Shutdown stops Notary module. +// Shutdown stops the Notary module. func (n *Notary) Shutdown() { close(n.stopCh) } -// OnNewRequest is a callback method which is called after new notary request is added to the notary request pool. +// OnNewRequest is a callback method which is called after a new notary request is added to the notary request pool. func (n *Notary) OnNewRequest(payload *payload.P2PNotaryRequest) { acc := n.getAccount() if acc == nil { @@ -223,7 +223,7 @@ func (n *Notary) OnNewRequest(payload *payload.P2PNotaryRequest) { r.minNotValidBefore = nvbFallback } } else { - // Avoid changes in main transaction witnesses got from notary request pool to + // Avoid changes in the main transaction witnesses got from the notary request pool to // keep the pooled tx valid. We will update its copy => the copy's size will be changed. cp := *payload.MainTransaction cp.Scripts = make([]transaction.Witness, len(payload.MainTransaction.Scripts)) @@ -239,7 +239,7 @@ func (n *Notary) OnNewRequest(payload *payload.P2PNotaryRequest) { if r.witnessInfo == nil && validationErr == nil { r.witnessInfo = newInfo } - // Allow modification of fallback transaction got from notary request pool. + // Allow modification of a fallback transaction got from the notary request pool. // It has dummy Notary witness attached => its size won't be changed. r.fallbacks = append(r.fallbacks, payload.FallbackTransaction) if exists && r.isMainCompleted() || validationErr != nil { @@ -325,7 +325,7 @@ func (n *Notary) OnRequestRemoval(pld *payload.P2PNotaryRequest) { } } -// PostPersist is a callback which is called after new block event is received. +// PostPersist is a callback which is called after a new block event is received. // PostPersist must not be called under the blockchain lock, because it uses finalization function. func (n *Notary) PostPersist() { acc := n.getAccount() @@ -443,7 +443,7 @@ func (n *Notary) newTxCallbackLoop() { } } -// updateTxSize returns transaction with re-calculated size and an error. +// updateTxSize returns a transaction with re-calculated size and an error. func updateTxSize(tx *transaction.Transaction) (*transaction.Transaction, error) { bw := io.NewBufBinWriter() tx.EncodeBinary(bw.BinWriter) @@ -453,8 +453,8 @@ func updateTxSize(tx *transaction.Transaction) (*transaction.Transaction, error) return transaction.NewTransactionFromBytes(tx.Bytes()) } -// verifyIncompleteWitnesses checks that tx either doesn't have all witnesses attached (in this case none of them -// can be multisignature), or it only has a partial multisignature. It returns the request type (sig/multisig), the +// verifyIncompleteWitnesses checks that the tx either doesn't have all witnesses attached (in this case none of them +// can be multisignature) or it only has a partial multisignature. It returns the request type (sig/multisig), the // number of signatures to be collected, sorted public keys (for multisig request only) and an error. func (n *Notary) verifyIncompleteWitnesses(tx *transaction.Transaction, nKeysExpected uint8) ([]witnessInfo, error) { var nKeysActual uint8 @@ -466,8 +466,8 @@ func (n *Notary) verifyIncompleteWitnesses(tx *transaction.Transaction, nKeysExp } result := make([]witnessInfo, len(tx.Signers)) for i, w := range tx.Scripts { - // Do not check witness for Notary contract -- it will be replaced by proper witness in any case. - // Also do not check other contract-based witnesses (they can be combined with anything) + // Do not check witness for a Notary contract -- it will be replaced by proper witness in any case. + // Also, do not check other contract-based witnesses (they can be combined with anything) if len(w.VerificationScript) == 0 { result[i] = witnessInfo{ typ: Contract, diff --git a/pkg/services/notary/request_type.go b/pkg/services/notary/request_type.go index 12c9526ea..13915091b 100644 --- a/pkg/services/notary/request_type.go +++ b/pkg/services/notary/request_type.go @@ -1,6 +1,6 @@ package notary -// RequestType represents the type of Notary request. +// RequestType represents type of Notary request. type RequestType byte const ( diff --git a/pkg/services/oracle/broadcaster/oracle.go b/pkg/services/oracle/broadcaster/oracle.go index db9aec096..29dd4a160 100644 --- a/pkg/services/oracle/broadcaster/oracle.go +++ b/pkg/services/oracle/broadcaster/oracle.go @@ -25,7 +25,7 @@ type oracleBroadcaster struct { rpcbroadcaster.RPCBroadcaster } -// New returns new struct capable of broadcasting oracle responses. +// New returns a new struct capable of broadcasting oracle responses. func New(cfg config.OracleConfiguration, log *zap.Logger) oracle.Broadcaster { if cfg.ResponseTimeout == 0 { cfg.ResponseTimeout = defaultSendTimeout diff --git a/pkg/services/oracle/jsonpath/jsonpath.go b/pkg/services/oracle/jsonpath/jsonpath.go index 061b3af55..18b1294ac 100644 --- a/pkg/services/oracle/jsonpath/jsonpath.go +++ b/pkg/services/oracle/jsonpath/jsonpath.go @@ -8,10 +8,10 @@ import ( ) type ( - // pathTokenType represents single JSONPath token. + // pathTokenType represents a single JSONPath token. pathTokenType byte - // pathParser combines JSONPath and a position to start parsing from. + // pathParser combines a JSONPath and a position to start parsing from. pathParser struct { s string i int @@ -39,7 +39,7 @@ const ( ) // Get returns substructures of value selected by path. -// The result is always non-nil unless path is invalid. +// The result is always non-nil unless the path is invalid. func Get(path string, value interface{}) ([]interface{}, bool) { if path == "" { return []interface{}{value}, true @@ -128,8 +128,8 @@ func (p *pathParser) nextToken() (pathTokenType, string) { return typ, value } -// parseString parses JSON string surrounded by single quotes. -// It returns number of characters were consumed and true on success. +// parseString parses a JSON string surrounded by single quotes. +// It returns the number of characters consumed and true on success. func (p *pathParser) parseString() (string, int, bool) { var end int for end = p.i + 1; end < len(p.s); end++ { @@ -141,8 +141,8 @@ func (p *pathParser) parseString() (string, int, bool) { return "", 0, false } -// parseIdent parses alphanumeric identifier. -// It returns number of characters were consumed and true on success. +// parseIdent parses an alphanumeric identifier. +// It returns the number of characters consumed and true on success. func (p *pathParser) parseIdent() (string, int, bool) { var end int for end = p.i + 1; end < len(p.s); end++ { @@ -156,9 +156,9 @@ func (p *pathParser) parseIdent() (string, int, bool) { return p.s[p.i:end], end - p.i, true } -// parseNumber parses integer number. +// parseNumber parses an integer number. // Only string representation is returned, size-checking is done on the first use. -// It also returns number of characters were consumed and true on success. +// It also returns the number of characters consumed and true on success. func (p *pathParser) parseNumber() (string, int, bool) { var end int for end = p.i + 1; end < len(p.s); end++ { @@ -402,7 +402,7 @@ func (p *pathParser) processUnion(objs []interface{}, firstTyp pathTokenType, fi } } -// processSlice processes slice with the specified start index. +// processSlice processes a slice with the specified start index. func (p *pathParser) processSlice(objs []interface{}, start int) ([]interface{}, bool) { typ, val := p.nextToken() switch typ { diff --git a/pkg/services/oracle/neofs/neofs.go b/pkg/services/oracle/neofs/neofs.go index 2af9afdfb..eb8ea7c35 100644 --- a/pkg/services/oracle/neofs/neofs.go +++ b/pkg/services/oracle/neofs/neofs.go @@ -38,7 +38,7 @@ var ( ErrInvalidCommand = errors.New("invalid command") ) -// Get returns neofs object from the provided url. +// Get returns a neofs object from the provided url. // URI scheme is "neofs://". // If Command is not provided, full object is requested. func Get(ctx context.Context, priv *keys.PrivateKey, u *url.URL, addr string) ([]byte, error) { diff --git a/pkg/services/oracle/network.go b/pkg/services/oracle/network.go index d4b096215..b4ee6ef02 100644 --- a/pkg/services/oracle/network.go +++ b/pkg/services/oracle/network.go @@ -51,16 +51,16 @@ func getDefaultClient(cfg config.OracleConfiguration) *http.Client { d := &net.Dialer{} if !cfg.AllowPrivateHost { // Control is used after request URI is resolved and network connection (network - // file descriptor) is created, but right before the moment listening/dialing + // file descriptor) is created, but right before listening/dialing // is started. - // `address` represents resolved IP address in the format of ip:port. `address` + // `address` represents a resolved IP address in the format of ip:port. `address` // is presented in its final (resolved) form that was used directly for network // connection establishing. // Control is called for each item in the set of IP addresses got from request // URI resolving. The first network connection with address that passes Control // function will be used for further request processing. Network connection // with address that failed Control will be ignored. If all the connections - // fail Control then the most relevant error (the one from the first address) + // fail Control, the most relevant error (the one from the first address) // will be returned after `Client.Do`. d.Control = func(network, address string, c syscall.RawConn) error { host, _, err := net.SplitHostPort(address) @@ -81,7 +81,7 @@ func getDefaultClient(cfg config.OracleConfiguration) *http.Client { client.Transport = &http.Transport{ DisableKeepAlives: true, // Do not set DialTLSContext, so that DialContext will be used to establish the - // connection. After that TLS connection will be added to a persistent connection + // connection. After that, TLS connection will be added to a persistent connection // by standard library code and handshaking will be performed. DialContext: d.DialContext, } diff --git a/pkg/services/oracle/oracle.go b/pkg/services/oracle/oracle.go index bd3a04e7c..1882d49d0 100644 --- a/pkg/services/oracle/oracle.go +++ b/pkg/services/oracle/oracle.go @@ -21,7 +21,7 @@ import ( ) type ( - // Ledger is the interface to Blockchain sufficient for Oracle. + // Ledger is an interface to Blockchain sufficient for Oracle. Ledger interface { BlockHeight() uint32 FeePerByte() int64 @@ -32,7 +32,7 @@ type ( GetTransaction(util.Uint256) (*transaction.Transaction, uint32, error) } - // Oracle represents oracle module capable of talking + // Oracle represents an oracle module capable of talking // with the external world. Oracle struct { Config @@ -100,13 +100,13 @@ type ( ) const ( - // defaultRequestTimeout is default request timeout. + // defaultRequestTimeout is the default request timeout. defaultRequestTimeout = time.Second * 5 - // defaultMaxTaskTimeout is default timeout for the request to be dropped if it can't be processed. + // defaultMaxTaskTimeout is the default timeout for the request to be dropped if it can't be processed. defaultMaxTaskTimeout = time.Hour - // defaultRefreshInterval is default timeout for the failed request to be reprocessed. + // defaultRefreshInterval is the default timeout for the failed request to be reprocessed. defaultRefreshInterval = time.Minute * 3 // maxRedirections is the number of allowed redirections for Oracle HTTPS request. diff --git a/pkg/services/oracle/request.go b/pkg/services/oracle/request.go index 469888db4..9eba982ac 100644 --- a/pkg/services/oracle/request.go +++ b/pkg/services/oracle/request.go @@ -87,7 +87,7 @@ func (o *Oracle) AddRequests(reqs map[uint64]*state.OracleRequest) { } } -// ProcessRequestsInternal processes provided requests synchronously. +// ProcessRequestsInternal processes the provided requests synchronously. func (o *Oracle) ProcessRequestsInternal(reqs map[uint64]*state.OracleRequest) { acc := o.getAccount() if acc == nil { @@ -194,7 +194,7 @@ func (o *Oracle) processRequest(priv *keys.PrivateKey, req request) error { if !errors.Is(err, storage.ErrKeyNotFound) { return err } - // The only reason tx can be not found is if it wasn't yet persisted from DAO. + // The only reason tx can be not found is that it hasn't been persisted from DAO yet. h = currentHeight } h += vubInc // Main tx is only valid for RequestHeight + ValidUntilBlock. diff --git a/pkg/services/oracle/response.go b/pkg/services/oracle/response.go index 779290b8a..b57be2f3b 100644 --- a/pkg/services/oracle/response.go +++ b/pkg/services/oracle/response.go @@ -27,8 +27,8 @@ func (o *Oracle) getResponse(reqID uint64, create bool) *incompleteTx { return incTx } -// AddResponse processes oracle response from node pub. -// sig is response transaction signature. +// AddResponse handles an oracle response (transaction signature for some identified request) signed by the given key. +// sig is a response transaction signature. func (o *Oracle) AddResponse(pub *keys.PublicKey, reqID uint64, txSig []byte) { incTx := o.getResponse(reqID, true) if incTx == nil { @@ -63,7 +63,7 @@ func (o *Oracle) AddResponse(pub *keys.PublicKey, reqID uint64, txSig []byte) { } } -// ErrResponseTooLarge is returned when response exceeds max allowed size. +// ErrResponseTooLarge is returned when a response exceeds the max allowed size. var ErrResponseTooLarge = errors.New("too big response") func readResponse(rc gio.ReadCloser, limit int) ([]byte, error) { @@ -80,7 +80,7 @@ func readResponse(rc gio.ReadCloser, limit int) ([]byte, error) { return nil, err } -// CreateResponseTx creates unsigned oracle response transaction. +// CreateResponseTx creates an unsigned oracle response transaction. func (o *Oracle) CreateResponseTx(gasForResponse int64, vub uint32, resp *transaction.OracleResponse) (*transaction.Transaction, error) { tx := transaction.New(o.oracleResponse, 0) tx.Nonce = uint32(resp.ID) @@ -134,9 +134,9 @@ func (o *Oracle) CreateResponseTx(gasForResponse int64, vub uint32, resp *transa } func (o *Oracle) testVerify(tx *transaction.Transaction) (int64, bool) { - // (*Blockchain).GetTestVM calls Hash() method of provided transaction; once being called, this + // (*Blockchain).GetTestVM calls Hash() method of the provided transaction; once being called, this // method caches transaction hash, but tx building is not yet completed and hash will be changed. - // So make a copy of tx to avoid wrong hash caching. + // So, make a copy of the tx to avoid wrong hash caching. cp := *tx ic := o.Chain.GetTestVM(trigger.Verification, &cp, nil) ic.VM.GasLimit = o.Chain.GetMaxVerificationGAS() diff --git a/pkg/services/oracle/transaction.go b/pkg/services/oracle/transaction.go index 5902afe7c..7f1ccc544 100644 --- a/pkg/services/oracle/transaction.go +++ b/pkg/services/oracle/transaction.go @@ -17,28 +17,28 @@ import ( type ( incompleteTx struct { sync.RWMutex - // isSent is true tx was already broadcasted. + // isSent is true if tx has been already broadcasted. isSent bool - // attempts is how many times request was processed. + // attempts is how many times the request was processed. attempts int - // time is the time when request was last processed. + // time is the time when the request was last processed. time time.Time - // request is oracle request. + // request is an oracle request. request *state.OracleRequest - // tx is oracle response transaction. + // tx is an oracle response transaction. tx *transaction.Transaction - // sigs contains signature from every oracle node. + // sigs contains a signature from every oracle node. sigs map[string]*txSignature - // backupTx is backup transaction. + // backupTx is a backup transaction. backupTx *transaction.Transaction // backupSigs contains signatures of backup tx. backupSigs map[string]*txSignature } txSignature struct { - // pub is cached public key. + // pub is a cached public key. pub *keys.PublicKey - // ok is true if signature was verified. + // ok is true if the signature was verified. ok bool // sig is tx signature. sig []byte @@ -81,7 +81,7 @@ func (t *incompleteTx) addResponse(pub *keys.PublicKey, sig []byte, isBackup boo } } -// finalize checks is either main or backup tx has sufficient number of signatures and returns +// finalize checks if either main or backup tx has sufficient number of signatures and returns // tx and bool value indicating if it is ready to be broadcasted. func (t *incompleteTx) finalize(oracleNodes keys.PublicKeys, backupOnly bool) (*transaction.Transaction, bool) { if !backupOnly && finalizeTx(oracleNodes, t.tx, t.sigs) { diff --git a/pkg/services/stateroot/message.go b/pkg/services/stateroot/message.go index 5b1e32e73..d96b6e239 100644 --- a/pkg/services/stateroot/message.go +++ b/pkg/services/stateroot/message.go @@ -11,7 +11,7 @@ type ( // MessageType represents message type. MessageType byte - // Message represents state-root related message. + // Message represents a state-root related message. Message struct { Type MessageType Payload io.Serializable @@ -24,7 +24,7 @@ const ( RootT MessageType = 1 ) -// NewMessage creates new message of specified type. +// NewMessage creates a new message of the specified type. func NewMessage(typ MessageType, p io.Serializable) *Message { return &Message{ Type: typ, @@ -32,13 +32,13 @@ func NewMessage(typ MessageType, p io.Serializable) *Message { } } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (m *Message) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(m.Type)) m.Payload.EncodeBinary(w) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (m *Message) DecodeBinary(r *io.BinReader) { switch m.Type = MessageType(r.ReadB()); m.Type { case VoteT: diff --git a/pkg/services/stateroot/network.go b/pkg/services/stateroot/network.go index a6c914c16..e2eedcd8f 100644 --- a/pkg/services/stateroot/network.go +++ b/pkg/services/stateroot/network.go @@ -19,7 +19,7 @@ const rootValidEndInc = 100 // RelayCallback represents callback for sending validated state roots. type RelayCallback = func(*payload.Extensible) -// AddSignature adds state root signature. +// AddSignature adds a state root signature. func (s *service) AddSignature(height uint32, validatorIndex int32, sig []byte) error { if !s.MainCfg.Enabled { return nil @@ -73,7 +73,7 @@ func (s *service) getIncompleteRoot(height uint32, myIndex byte) *incompleteRoot return incRoot } -// trySendRoot attempts to finalize and send MPTRoot, it must be called with ir locked. +// trySendRoot attempts to finalize and send MPTRoot, it must be called with the ir locked. func (s *service) trySendRoot(ir *incompleteRoot, acc *wallet.Account) { if !ir.isSenderNow() { return diff --git a/pkg/services/stateroot/service.go b/pkg/services/stateroot/service.go index e643d65bf..5766066df 100644 --- a/pkg/services/stateroot/service.go +++ b/pkg/services/stateroot/service.go @@ -18,7 +18,7 @@ import ( ) type ( - // Ledger is the interface to Blockchain sufficient for Service. + // Ledger is an interface to Blockchain sufficient for Service. Ledger interface { GetConfig() config.ProtocolConfiguration HeaderHeight() uint32 @@ -26,7 +26,7 @@ type ( UnsubscribeFromBlocks(ch chan<- *block.Block) } - // Service represents state root service. + // Service represents a state root service. Service interface { Name() string OnPayload(p *payload.Extensible) error @@ -62,11 +62,11 @@ type ( ) const ( - // Category is message category for extensible payloads. + // Category is a message category for extensible payloads. Category = "StateService" ) -// New returns new state root service instance using underlying module. +// New returns a new state root service instance using the underlying module. func New(cfg config.StateRoot, sm *stateroot.Module, log *zap.Logger, bc Ledger, cb RelayCallback) (Service, error) { bcConf := bc.GetConfig() s := &service{ diff --git a/pkg/services/stateroot/signature.go b/pkg/services/stateroot/signature.go index fb989fb00..66111d85a 100644 --- a/pkg/services/stateroot/signature.go +++ b/pkg/services/stateroot/signature.go @@ -18,11 +18,11 @@ type ( sync.RWMutex // svList is a list of state validator keys for this stateroot. svList keys.PublicKeys - // isSent is true state root was already broadcasted. + // isSent is true if the state root was already broadcasted. isSent bool - // request is oracle request. + // request is an oracle request. root *state.MPTRoot - // sigs contains signature from every oracle node. + // sigs contains a signature from every oracle node. sigs map[string]*rootSig // myIndex is the index of validator for this root. myIndex int @@ -33,11 +33,11 @@ type ( } rootSig struct { - // pub is cached public key. + // pub is a cached public key. pub *keys.PublicKey - // ok is true if signature was verified. + // ok is true if the signature was verified. ok bool - // sig is state root signature. + // sig is a state root signature. sig []byte } ) @@ -73,7 +73,7 @@ func (r *incompleteRoot) isSenderNow() bool { return ind == r.myIndex } -// finalize checks is either main or backup tx has sufficient number of signatures and returns +// finalize checks if either main or backup tx has sufficient number of signatures and returns // tx and bool value indicating if it is ready to be broadcasted. func (r *incompleteRoot) finalize() (*state.MPTRoot, bool) { if r.root == nil { diff --git a/pkg/services/stateroot/validators.go b/pkg/services/stateroot/validators.go index 1b8619a64..e762e6331 100644 --- a/pkg/services/stateroot/validators.go +++ b/pkg/services/stateroot/validators.go @@ -113,8 +113,8 @@ func (s *service) signAndSend(r *state.MPTRoot) error { return nil } -// sendVote attempts to send vote if it's still valid and if stateroot message -// was not sent yet. It must be called with ir locked. +// sendVote attempts to send a vote if it's still valid and if stateroot message +// has not been sent yet. It must be called with the ir locked. func (s *service) sendVote(ir *incompleteRoot) { if ir.isSent || ir.retries >= s.maxRetries || s.chain.HeaderHeight() >= ir.myVote.ValidBlockEnd { @@ -133,7 +133,7 @@ func (s *service) sendVote(ir *incompleteRoot) { ir.retries++ } -// getAccount returns current index and account for the node running this service. +// getAccount returns the current index and account for the node running this service. func (s *service) getAccount() (byte, *wallet.Account) { s.accMtx.RLock() defer s.accMtx.RUnlock() diff --git a/pkg/services/stateroot/vote.go b/pkg/services/stateroot/vote.go index ad0bd9316..73b1aed37 100644 --- a/pkg/services/stateroot/vote.go +++ b/pkg/services/stateroot/vote.go @@ -5,21 +5,21 @@ import ( "github.com/nspcc-dev/neo-go/pkg/io" ) -// Vote represents vote message. +// Vote represents a vote message. type Vote struct { ValidatorIndex int32 Height uint32 Signature []byte } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (p *Vote) EncodeBinary(w *io.BinWriter) { w.WriteU32LE(uint32(p.ValidatorIndex)) w.WriteU32LE(p.Height) w.WriteVarBytes(p.Signature) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (p *Vote) DecodeBinary(r *io.BinReader) { p.ValidatorIndex = int32(r.ReadU32LE()) p.Height = r.ReadU32LE() diff --git a/pkg/smartcontract/binding/generate.go b/pkg/smartcontract/binding/generate.go index 8791862aa..5ac2f2e00 100644 --- a/pkg/smartcontract/binding/generate.go +++ b/pkg/smartcontract/binding/generate.go @@ -78,7 +78,7 @@ type ( } ) -// NewConfig initializes and returns new config instance. +// NewConfig initializes and returns a new config instance. func NewConfig() Config { return Config{ Overrides: make(map[string]Override), diff --git a/pkg/smartcontract/binding/override.go b/pkg/smartcontract/binding/override.go index 632a0f44f..366bd562e 100644 --- a/pkg/smartcontract/binding/override.go +++ b/pkg/smartcontract/binding/override.go @@ -4,9 +4,9 @@ import ( "strings" ) -// Override contains package and type to replace manifest method parameter type with. +// Override contains a package and a type to replace manifest method parameter type with. type Override struct { - // Package contains fully-qualified package name. + // Package contains a fully-qualified package name. Package string // TypeName contains type name together with a package alias. TypeName string diff --git a/pkg/smartcontract/callflag/call_flags.go b/pkg/smartcontract/callflag/call_flags.go index cad3994d8..224077c4b 100644 --- a/pkg/smartcontract/callflag/call_flags.go +++ b/pkg/smartcontract/callflag/call_flags.go @@ -6,7 +6,7 @@ import ( "strings" ) -// CallFlag represents call flag. +// CallFlag represents a call flag. type CallFlag byte // Default flags. @@ -34,12 +34,12 @@ var flagString = map[CallFlag]string{ } // basicFlags are all flags except All and None. It's used to stringify CallFlag -// where its bits are matched against these values from values with sets of bits -// to simple flags which is important to produce proper string representation +// where its bits are matched against these values from the values with sets of bits +// to simple flags, which is important to produce proper string representation // matching C# Enum handling. var basicFlags = []CallFlag{ReadOnly, States, ReadStates, WriteStates, AllowCall, AllowNotify} -// FromString parses input string and returns corresponding CallFlag. +// FromString parses an input string and returns a corresponding CallFlag. func FromString(s string) (CallFlag, error) { flags := strings.Split(s, ",") if len(flags) == 0 { @@ -99,12 +99,12 @@ func (f CallFlag) String() string { return res } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (f CallFlag) MarshalJSON() ([]byte, error) { return []byte(`"` + f.String() + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (f *CallFlag) UnmarshalJSON(data []byte) error { var js string if err := json.Unmarshal(data, &js); err != nil { diff --git a/pkg/smartcontract/context/context.go b/pkg/smartcontract/context/context.go index acfadd89e..fd768604d 100644 --- a/pkg/smartcontract/context/context.go +++ b/pkg/smartcontract/context/context.go @@ -157,7 +157,7 @@ func (c *ParameterContext) getItemForContract(h util.Uint160, ctr *wallet.Contra return item } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c ParameterContext) MarshalJSON() ([]byte, error) { verif, err := c.Verifiable.EncodeHashableFields() if err != nil { @@ -181,7 +181,7 @@ func (c ParameterContext) MarshalJSON() ([]byte, error) { return json.Marshal(pc) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (c *ParameterContext) UnmarshalJSON(data []byte) error { pc := new(paramContext) if err := json.Unmarshal(data, pc); err != nil { diff --git a/pkg/smartcontract/context/item.go b/pkg/smartcontract/context/item.go index b648b04f2..ffa5b7da9 100644 --- a/pkg/smartcontract/context/item.go +++ b/pkg/smartcontract/context/item.go @@ -14,12 +14,12 @@ type Item struct { Signatures map[string][]byte `json:"signatures"` } -// GetSignature returns signature for pub if present. +// GetSignature returns a signature for the pub if present. func (it *Item) GetSignature(pub *keys.PublicKey) []byte { return it.Signatures[hex.EncodeToString(pub.Bytes())] } -// AddSignature adds a signature for pub. +// AddSignature adds a signature for the pub. func (it *Item) AddSignature(pub *keys.PublicKey, sig []byte) { pubHex := hex.EncodeToString(pub.Bytes()) it.Signatures[pubHex] = sig diff --git a/pkg/smartcontract/manifest/abi.go b/pkg/smartcontract/manifest/abi.go index 8d8f97c76..15f89daf4 100644 --- a/pkg/smartcontract/manifest/abi.go +++ b/pkg/smartcontract/manifest/abi.go @@ -17,7 +17,7 @@ const ( // MethodVerify is a name for default verification method. MethodVerify = "verify" - // MethodOnNEP17Payment is name of the method which is called when contract receives NEP-17 tokens. + // MethodOnNEP17Payment is the name of the method which is called when contract receives NEP-17 tokens. MethodOnNEP17Payment = "onNEP17Payment" // MethodOnNEP11Payment is the name of the method which is called when contract receives NEP-11 tokens. @@ -40,7 +40,7 @@ func (a *ABI) GetMethod(name string, paramCount int) *Method { return nil } -// GetEvent returns event with the specified name. +// GetEvent returns the event with the specified name. func (a *ABI) GetEvent(name string) *Event { for i := range a.Events { if a.Events[i].Name == name { diff --git a/pkg/smartcontract/manifest/container.go b/pkg/smartcontract/manifest/container.go index e125b5fbf..f99132a48 100644 --- a/pkg/smartcontract/manifest/container.go +++ b/pkg/smartcontract/manifest/container.go @@ -1,7 +1,7 @@ package manifest // This file contains types and helper methods for wildcard containers. -// Wildcard container can contain either a finite set of elements or +// A wildcard container can contain either a finite set of elements or // every possible element, in which case it is named `wildcard`. import ( @@ -9,12 +9,12 @@ import ( "encoding/json" ) -// WildStrings represents string set which can be wildcard. +// WildStrings represents a string set which can be a wildcard. type WildStrings struct { Value []string } -// WildPermissionDescs represents PermissionDescriptor set which can be wildcard. +// WildPermissionDescs represents a PermissionDescriptor set which can be a wildcard. type WildPermissionDescs struct { Value []PermissionDesc } @@ -45,16 +45,16 @@ func (c *WildPermissionDescs) Contains(v PermissionDesc) bool { return false } -// IsWildcard returns true iff container is wildcard. +// IsWildcard returns true iff the container is a wildcard. func (c *WildStrings) IsWildcard() bool { return c.Value == nil } -// IsWildcard returns true iff container is wildcard. +// IsWildcard returns true iff the container is a wildcard. func (c *WildPermissionDescs) IsWildcard() bool { return c.Value == nil } -// Restrict transforms container into an empty one. +// Restrict transforms the container into an empty one. func (c *WildStrings) Restrict() { c.Value = []string{} } -// Restrict transforms container into an empty one. +// Restrict transforms the container into an empty one. func (c *WildPermissionDescs) Restrict() { c.Value = []PermissionDesc{} } // Add adds v to the container. @@ -63,7 +63,7 @@ func (c *WildStrings) Add(v string) { c.Value = append(c.Value, v) } // Add adds v to the container. func (c *WildPermissionDescs) Add(v PermissionDesc) { c.Value = append(c.Value, v) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c WildStrings) MarshalJSON() ([]byte, error) { if c.IsWildcard() { return []byte(`"*"`), nil @@ -71,7 +71,7 @@ func (c WildStrings) MarshalJSON() ([]byte, error) { return json.Marshal(c.Value) } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (c WildPermissionDescs) MarshalJSON() ([]byte, error) { if c.IsWildcard() { return []byte(`"*"`), nil @@ -79,7 +79,7 @@ func (c WildPermissionDescs) MarshalJSON() ([]byte, error) { return json.Marshal(c.Value) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (c *WildStrings) UnmarshalJSON(data []byte) error { if !bytes.Equal(data, []byte(`"*"`)) { ss := []string{} @@ -91,7 +91,7 @@ func (c *WildStrings) UnmarshalJSON(data []byte) error { return nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (c *WildPermissionDescs) UnmarshalJSON(data []byte) error { if !bytes.Equal(data, []byte(`"*"`)) { us := []PermissionDesc{} diff --git a/pkg/smartcontract/manifest/group.go b/pkg/smartcontract/manifest/group.go index 1e5a942e2..11c59fdff 100644 --- a/pkg/smartcontract/manifest/group.go +++ b/pkg/smartcontract/manifest/group.go @@ -14,8 +14,8 @@ import ( ) // Group represents a group of smartcontracts identified by a public key. -// Every SC in a group must provide signature of it's hash to prove -// it belongs to a group. +// Every SC in a group must provide signature of its hash to prove +// it belongs to the group. type Group struct { PublicKey *keys.PublicKey `json:"pubkey"` Signature []byte `json:"signature"` @@ -29,7 +29,7 @@ type groupAux struct { Signature []byte `json:"signature"` } -// IsValid checks whether group's signature corresponds to the given hash. +// IsValid checks whether the group's signature corresponds to the given hash. func (g *Group) IsValid(h util.Uint160) error { if !g.PublicKey.Verify(g.Signature, hash.Sha256(h.BytesBE()).BytesBE()) { return errors.New("incorrect group signature") @@ -73,7 +73,7 @@ func (g Groups) Contains(k *keys.PublicKey) bool { return false } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (g *Group) MarshalJSON() ([]byte, error) { aux := &groupAux{ PublicKey: hex.EncodeToString(g.PublicKey.Bytes()), @@ -82,7 +82,7 @@ func (g *Group) MarshalJSON() ([]byte, error) { return json.Marshal(aux) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (g *Group) UnmarshalJSON(data []byte) error { aux := new(groupAux) if err := json.Unmarshal(data, aux); err != nil { diff --git a/pkg/smartcontract/manifest/manifest.go b/pkg/smartcontract/manifest/manifest.go index 4f25c5416..b5264f88a 100644 --- a/pkg/smartcontract/manifest/manifest.go +++ b/pkg/smartcontract/manifest/manifest.go @@ -12,7 +12,7 @@ import ( ) const ( - // MaxManifestSize is a max length for a valid contract manifest. + // MaxManifestSize is the max length for a valid contract manifest. MaxManifestSize = math.MaxUint16 // NEP11StandardName represents the name of NEP-11 smartcontract standard. @@ -44,7 +44,7 @@ type Manifest struct { Extra json.RawMessage `json:"extra"` } -// NewManifest returns new manifest with necessary fields initialized. +// NewManifest returns a new manifest with necessary fields initialized. func NewManifest(name string) *Manifest { m := &Manifest{ Name: name, @@ -62,15 +62,15 @@ func NewManifest(name string) *Manifest { return m } -// DefaultManifest returns default contract manifest. +// DefaultManifest returns the default contract manifest. func DefaultManifest(name string) *Manifest { m := NewManifest(name) m.Permissions = []Permission{*NewPermission(PermissionWildcard)} return m } -// CanCall returns true is current contract is allowed to call -// method of another contract with specified hash. +// CanCall returns true if the current contract is allowed to call +// the method of another contract with the specified hash. func (m *Manifest) CanCall(hash util.Uint160, toCall *Manifest, method string) bool { for i := range m.Permissions { if m.Permissions[i].IsAllowed(hash, toCall, method) { @@ -119,7 +119,7 @@ func (m *Manifest) IsValid(hash util.Uint160) error { return Permissions(m.Permissions).AreValid() } -// IsStandardSupported denotes whether the specified standard supported by the contract. +// IsStandardSupported denotes whether the specified standard is supported by the contract. func (m *Manifest) IsStandardSupported(standard string) bool { for _, st := range m.SupportedStandards { if st == standard { diff --git a/pkg/smartcontract/manifest/parameter.go b/pkg/smartcontract/manifest/parameter.go index cbee93dbc..88445adde 100644 --- a/pkg/smartcontract/manifest/parameter.go +++ b/pkg/smartcontract/manifest/parameter.go @@ -17,7 +17,7 @@ type Parameter struct { // Parameters is just an array of Parameter. type Parameters []Parameter -// NewParameter returns new parameter of specified name and type. +// NewParameter returns a new parameter of the specified name and type. func NewParameter(name string, typ smartcontract.ParamType) Parameter { return Parameter{ Name: name, @@ -91,7 +91,7 @@ func (p Parameters) AreValid() error { return nil } -// stringsHaveDups checks given set of strings for duplicates. It modifies the slice given! +// stringsHaveDups checks the given set of strings for duplicates. It modifies the slice given! func stringsHaveDups(strings []string) bool { sort.Strings(strings) for i := range strings { @@ -105,7 +105,7 @@ func stringsHaveDups(strings []string) bool { return false } -// permissionDescsHaveDups checks given set of strings for duplicates. It modifies the slice given! +// permissionDescsHaveDups checks the given set of strings for duplicates. It modifies the slice given! func permissionDescsHaveDups(descs []PermissionDesc) bool { sort.Slice(descs, func(i, j int) bool { return descs[i].Less(descs[j]) diff --git a/pkg/smartcontract/manifest/permission.go b/pkg/smartcontract/manifest/permission.go index bbbb7d084..0859871db 100644 --- a/pkg/smartcontract/manifest/permission.go +++ b/pkg/smartcontract/manifest/permission.go @@ -44,7 +44,7 @@ type permissionAux struct { Methods WildStrings `json:"methods"` } -// NewPermission returns new permission of a given type. +// NewPermission returns a new permission of the given type. func NewPermission(typ PermissionType, args ...interface{}) *Permission { return &Permission{ Contract: *newPermissionDesc(typ, args...), @@ -88,7 +88,7 @@ func (d *PermissionDesc) Group() *keys.PublicKey { return d.Value.(*keys.PublicKey) } -// Less returns true if this value is less than given PermissionDesc value. +// Less returns true if this value is less than the given PermissionDesc value. func (d *PermissionDesc) Less(d1 PermissionDesc) bool { if d.Type < d1.Type { return true @@ -158,7 +158,7 @@ func (ps Permissions) AreValid() error { return nil } -// IsAllowed checks if method is allowed to be executed. +// IsAllowed checks if the method is allowed to be executed. func (p *Permission) IsAllowed(hash util.Uint160, m *Manifest, method string) bool { switch p.Contract.Type { case PermissionWildcard: @@ -187,7 +187,7 @@ func (p *Permission) IsAllowed(hash util.Uint160, m *Manifest, method string) bo return p.Methods.Contains(method) } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (p *Permission) UnmarshalJSON(data []byte) error { aux := new(permissionAux) if err := json.Unmarshal(data, aux); err != nil { @@ -198,7 +198,7 @@ func (p *Permission) UnmarshalJSON(data []byte) error { return nil } -// MarshalJSON implements json.Marshaler interface. +// MarshalJSON implements the json.Marshaler interface. func (d *PermissionDesc) MarshalJSON() ([]byte, error) { switch d.Type { case PermissionHash: @@ -210,7 +210,7 @@ func (d *PermissionDesc) MarshalJSON() ([]byte, error) { } } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (d *PermissionDesc) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { diff --git a/pkg/smartcontract/manifest/standard/comply.go b/pkg/smartcontract/manifest/standard/comply.go index 26a87a391..ab7a3a2bd 100644 --- a/pkg/smartcontract/manifest/standard/comply.go +++ b/pkg/smartcontract/manifest/standard/comply.go @@ -25,8 +25,8 @@ var checks = map[string][]*Standard{ manifest.NEP17Payable: {nep17payable}, } -// Check checks if manifest complies with all provided standards. -// Currently only NEP-17 is supported. +// Check checks if the manifest complies with all provided standards. +// Currently, only NEP-17 is supported. func Check(m *manifest.Manifest, standards ...string) error { return check(m, true, standards...) } diff --git a/pkg/smartcontract/manifest/standard/doc.go b/pkg/smartcontract/manifest/standard/doc.go index 9b22b93ac..a4fd70c9b 100644 --- a/pkg/smartcontract/manifest/standard/doc.go +++ b/pkg/smartcontract/manifest/standard/doc.go @@ -1,5 +1,5 @@ /* Package standard contains interfaces for well-defined standards -and function for checking if arbitrary manifest complies with them. +and a function for checking if an arbitrary manifest complies with them. */ package standard diff --git a/pkg/smartcontract/nef/nef.go b/pkg/smartcontract/nef/nef.go index d8d30ec8d..dd427a656 100644 --- a/pkg/smartcontract/nef/nef.go +++ b/pkg/smartcontract/nef/nef.go @@ -39,7 +39,7 @@ const ( compilerFieldSize = 64 ) -// File represents compiled contract file structure according to the NEF3 standard. +// File represents a compiled contract file structure according to the NEF3 standard. type File struct { Header Source string `json:"source"` @@ -48,13 +48,13 @@ type File struct { Checksum uint32 `json:"checksum"` } -// Header represents File header. +// Header represents a File header. type Header struct { Magic uint32 `json:"magic"` Compiler string `json:"compiler"` } -// NewFile returns new NEF3 file with script specified. +// NewFile returns a new NEF3 file with the script specified. func NewFile(script []byte) (*File, error) { file := &File{ Header: Header{ @@ -71,7 +71,7 @@ func NewFile(script []byte) (*File, error) { return file, nil } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (h *Header) EncodeBinary(w *io.BinWriter) { w.WriteU32LE(h.Magic) if len(h.Compiler) > compilerFieldSize { @@ -83,7 +83,7 @@ func (h *Header) EncodeBinary(w *io.BinWriter) { w.WriteBytes(b) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (h *Header) DecodeBinary(r *io.BinReader) { h.Magic = r.ReadU32LE() if h.Magic != Magic { @@ -107,7 +107,7 @@ func (n *File) CalculateChecksum() uint32 { return binary.LittleEndian.Uint32(hash.Checksum(bb[:len(bb)-4])) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (n *File) EncodeBinary(w *io.BinWriter) { n.Header.EncodeBinary(w) if len(n.Source) > MaxSourceURLLength { @@ -124,7 +124,7 @@ func (n *File) EncodeBinary(w *io.BinWriter) { var errInvalidReserved = errors.New("reserved bytes must be 0") -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (n *File) DecodeBinary(r *io.BinReader) { n.Header.DecodeBinary(r) n.Source = r.ReadString(MaxSourceURLLength) @@ -152,7 +152,7 @@ func (n *File) DecodeBinary(r *io.BinReader) { } } -// Bytes returns byte array with serialized NEF File. +// Bytes returns a byte array with a serialized NEF File. func (n File) Bytes() ([]byte, error) { buf := io.NewBufBinWriter() n.EncodeBinary(buf.BinWriter) @@ -162,7 +162,7 @@ func (n File) Bytes() ([]byte, error) { return buf.Bytes(), nil } -// FileFromBytes returns NEF File deserialized from given bytes. +// FileFromBytes returns a NEF File deserialized from the given bytes. func FileFromBytes(source []byte) (File, error) { result := File{} r := io.NewBinReaderFromBuf(source) diff --git a/pkg/smartcontract/param_type.go b/pkg/smartcontract/param_type.go index 1f432536b..cef9512d1 100644 --- a/pkg/smartcontract/param_type.go +++ b/pkg/smartcontract/param_type.go @@ -96,7 +96,7 @@ func (pt ParamType) MarshalJSON() ([]byte, error) { return []byte(`"` + pt.String() + `"`), nil } -// UnmarshalJSON implements json.Unmarshaler interface. +// UnmarshalJSON implements the json.Unmarshaler interface. func (pt *ParamType) UnmarshalJSON(data []byte) error { var s string if err := json.Unmarshal(data, &s); err != nil { @@ -129,12 +129,12 @@ func (pt *ParamType) UnmarshalYAML(unmarshal func(interface{}) error) error { return err } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (pt ParamType) EncodeBinary(w *io.BinWriter) { w.WriteB(byte(pt)) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (pt *ParamType) DecodeBinary(r *io.BinReader) { *pt = ParamType(r.ReadB()) } @@ -246,7 +246,7 @@ func adjustValToType(typ ParamType, val string) (interface{}, error) { } // inferParamType tries to infer the value type from its contents. It returns -// IntegerType for anything that looks like decimal integer (can be converted +// IntegerType for anything that looks like a decimal integer (can be converted // with strconv.Atoi), BoolType for true and false values, Hash160Type for // addresses and hex strings encoding 20 bytes long values, PublicKeyType for // valid hex-encoded public keys, Hash256Type for hex-encoded 32 bytes values, @@ -291,7 +291,7 @@ func inferParamType(val string) ParamType { return StringType } -// ConvertToParamType converts provided value to parameter type if it's a valid type. +// ConvertToParamType converts the provided value to the parameter type if it's a valid type. func ConvertToParamType(val int) (ParamType, error) { if validParamTypes[ParamType(val)] { return ParamType(val), nil diff --git a/pkg/smartcontract/parameter.go b/pkg/smartcontract/parameter.go index 55683fa1a..97cb04a2c 100644 --- a/pkg/smartcontract/parameter.go +++ b/pkg/smartcontract/parameter.go @@ -28,14 +28,14 @@ type Parameter struct { Value interface{} `json:"value"` } -// ParameterPair represents key-value pair, a slice of which is stored in +// ParameterPair represents a key-value pair, a slice of which is stored in // MapType Parameter. type ParameterPair struct { Key Parameter `json:"key"` Value Parameter `json:"value"` } -// NewParameter returns a Parameter with proper initialized Value +// NewParameter returns a Parameter with a proper initialized Value // of the given ParamType. func NewParameter(t ParamType) Parameter { return Parameter{ @@ -49,7 +49,7 @@ type rawParameter struct { Value json.RawMessage `json:"value,omitempty"` } -// MarshalJSON implements Marshaler interface. +// MarshalJSON implements the Marshaler interface. func (p Parameter) MarshalJSON() ([]byte, error) { var ( resultRawValue json.RawMessage @@ -101,7 +101,7 @@ func (p Parameter) MarshalJSON() ([]byte, error) { }) } -// UnmarshalJSON implements Unmarshaler interface. +// UnmarshalJSON implements the Unmarshaler interface. func (p *Parameter) UnmarshalJSON(data []byte) (err error) { var ( r rawParameter @@ -313,7 +313,7 @@ func bytesToUint64(b []byte, size int) (uint64, error) { // NewParameterFromString returns a new Parameter initialized from the given // string in neo-go-specific format. It is intended to be used in user-facing -// interfaces and has some heuristics in it to simplify parameter passing. Exact +// interfaces and has some heuristics in it to simplify parameter passing. The exact // syntax is documented in the cli documentation. func NewParameterFromString(in string) (*Parameter, error) { var ( @@ -375,8 +375,8 @@ func NewParameterFromString(in string) (*Parameter, error) { return res, nil } -// ExpandParameterToEmitable converts parameter to a type which can be handled as -// an array item by emit.Array. It correlates with the way RPC server handles +// ExpandParameterToEmitable converts a parameter to a type which can be handled as +// an array item by emit.Array. It correlates with the way an RPC server handles // FuncParams for invoke* calls inside the request.ExpandArrayIntoScript function. func ExpandParameterToEmitable(param Parameter) (interface{}, error) { var err error diff --git a/pkg/smartcontract/trigger/trigger_type.go b/pkg/smartcontract/trigger/trigger_type.go index 86a00ff39..594344aed 100644 --- a/pkg/smartcontract/trigger/trigger_type.go +++ b/pkg/smartcontract/trigger/trigger_type.go @@ -7,23 +7,23 @@ import ( //go:generate stringer -type=Type -output=trigger_type_string.go -// Type represents trigger type used in C# reference node: https://github.com/neo-project/neo/blob/c64748ecbac3baeb8045b16af0d518398a6ced24/neo/SmartContract/TriggerType.cs#L3 +// Type represents a trigger type used in C# reference node: https://github.com/neo-project/neo/blob/c64748ecbac3baeb8045b16af0d518398a6ced24/neo/SmartContract/TriggerType.cs#L3 type Type byte // Viable list of supported trigger type constants. const ( - // OnPersist is a trigger type that indicates that script is being invoked + // OnPersist is a trigger type that indicates that the script is being invoked // internally by the system during block persistence (before transaction // processing). OnPersist Type = 0x01 - // PostPersist is a trigger type that indicates that script is being invoked + // PostPersist is a trigger type that indicates that the script is being invoked // by the system after block persistence (transcation processing) has // finished. PostPersist Type = 0x02 // The verification trigger indicates that the contract is being invoked as a verification function. - // The verification function can accept multiple parameters, and should return a boolean value that indicates the validity of the transaction or block. + // The verification function can accept multiple parameters and should return a boolean value that indicates the validity of the transaction or block. // The entry point of the contract will be invoked if the contract is triggered by Verification: // main(...); // The entry point of the contract must be able to handle this type of invocation. @@ -40,7 +40,7 @@ const ( All Type = OnPersist | PostPersist | Verification | Application ) -// FromString converts string to trigger Type. +// FromString converts a string to the trigger Type. func FromString(str string) (Type, error) { triggers := []Type{OnPersist, PostPersist, Verification, Application, All} str = strings.ToLower(str) diff --git a/pkg/util/bitfield/bitfield.go b/pkg/util/bitfield/bitfield.go index c2de953b4..62f51c5da 100644 --- a/pkg/util/bitfield/bitfield.go +++ b/pkg/util/bitfield/bitfield.go @@ -11,26 +11,26 @@ type Field []uint64 // Bits and bytes count in a basic element of Field. const elemBits = 64 -// New creates a new bit field of specified length. Actual field length +// New creates a new bit field of the specified length. Actual field length // can be rounded to the next multiple of 64, so it's a responsibility // of the user to deal with that. func New(n int) Field { return make(Field, 1+(n-1)/elemBits) } -// Set sets one bit at specified offset. No bounds checking is done. +// Set sets one bit at the specified offset. No bounds checking is done. func (f Field) Set(i int) { addr, offset := (i / elemBits), (i % elemBits) f[addr] |= (1 << offset) } -// IsSet returns true if the bit with specified offset is set. +// IsSet returns true if the bit with the specified offset is set. func (f Field) IsSet(i int) bool { addr, offset := (i / elemBits), (i % elemBits) return (f[addr] & (1 << offset)) != 0 } -// Copy makes a copy of current Field. +// Copy makes a copy of the current Field. func (f Field) Copy() Field { fn := make(Field, len(f)) copy(fn, f) diff --git a/pkg/util/uint160.go b/pkg/util/uint160.go index 3ce5b65ae..3ac8d0eec 100644 --- a/pkg/util/uint160.go +++ b/pkg/util/uint160.go @@ -16,7 +16,7 @@ const Uint160Size = 20 // Uint160 is a 20 byte long unsigned integer. type Uint160 [Uint160Size]uint8 -// Uint160DecodeStringBE attempts to decode the given string into an Uint160. +// Uint160DecodeStringBE attempts to decode the given string into a Uint160. func Uint160DecodeStringBE(s string) (Uint160, error) { var u Uint160 if len(s) != Uint160Size*2 { @@ -30,7 +30,7 @@ func Uint160DecodeStringBE(s string) (Uint160, error) { } // Uint160DecodeStringLE attempts to decode the given string -// in little-endian hex encoding into an Uint160. +// in little-endian hex encoding into a Uint160. func Uint160DecodeStringLE(s string) (Uint160, error) { var u Uint160 if len(s) != Uint160Size*2 { @@ -45,7 +45,7 @@ func Uint160DecodeStringLE(s string) (Uint160, error) { return Uint160DecodeBytesLE(b) } -// Uint160DecodeBytesBE attempts to decode the given bytes into an Uint160. +// Uint160DecodeBytesBE attempts to decode the given bytes into a Uint160. func Uint160DecodeBytesBE(b []byte) (u Uint160, err error) { if len(b) != Uint160Size { return u, fmt.Errorf("expected byte size of %d got %d", Uint160Size, len(b)) @@ -55,7 +55,7 @@ func Uint160DecodeBytesBE(b []byte) (u Uint160, err error) { } // Uint160DecodeBytesLE attempts to decode the given bytes in little-endian -// into an Uint160. +// into a Uint160. func Uint160DecodeBytesLE(b []byte) (u Uint160, err error) { if len(b) != Uint160Size { return u, fmt.Errorf("expected byte size of %d got %d", Uint160Size, len(b)) @@ -93,7 +93,7 @@ func (u Uint160) StringLE() string { return hex.EncodeToString(u.BytesLE()) } -// Reverse returns reversed representation of u. +// Reverse returns a reversed representation of u. func (u Uint160) Reverse() (r Uint160) { for i := 0; i < Uint160Size; i++ { r[i] = u[Uint160Size-i-1] @@ -107,7 +107,7 @@ func (u Uint160) Equals(other Uint160) bool { return u == other } -// Less returns true if this value is less than given Uint160 value. It's +// Less returns true if this value is less than the given Uint160 value. It's // primarily intended to be used for sorting purposes. func (u Uint160) Less(other Uint160) bool { for k := range u { @@ -154,12 +154,12 @@ func (u Uint160) MarshalYAML() (interface{}, error) { return "0x" + u.StringLE(), nil } -// EncodeBinary implements Serializable interface. +// EncodeBinary implements the Serializable interface. func (u *Uint160) EncodeBinary(bw *io.BinWriter) { bw.WriteBytes(u[:]) } -// DecodeBinary implements Serializable interface. +// DecodeBinary implements the Serializable interface. func (u *Uint160) DecodeBinary(br *io.BinReader) { br.ReadBytes(u[:]) } diff --git a/pkg/util/uint256.go b/pkg/util/uint256.go index d7dd76aa2..303ba5221 100644 --- a/pkg/util/uint256.go +++ b/pkg/util/uint256.go @@ -17,7 +17,7 @@ const Uint256Size = 32 // Uint256 is a 32 byte long unsigned integer. type Uint256 [Uint256Size]uint8 -// Uint256DecodeStringLE attempts to decode the given string (in LE representation) into an Uint256. +// Uint256DecodeStringLE attempts to decode the given string (in LE representation) into a Uint256. func Uint256DecodeStringLE(s string) (u Uint256, err error) { if len(s) != Uint256Size*2 { return u, fmt.Errorf("expected string size of %d got %d", Uint256Size*2, len(s)) @@ -31,7 +31,7 @@ func Uint256DecodeStringLE(s string) (u Uint256, err error) { } // Uint256DecodeStringBE attempts to decode the given string (in BE representation) -// into an Uint256. +// into a Uint256. func Uint256DecodeStringBE(s string) (u Uint256, err error) { if len(s) != Uint256Size*2 { return u, fmt.Errorf("expected string size of %d got %d", Uint256Size*2, len(s)) @@ -45,7 +45,7 @@ func Uint256DecodeStringBE(s string) (u Uint256, err error) { return Uint256DecodeBytesBE(b) } -// Uint256DecodeBytesBE attempts to decode the given string (in BE representation) into an Uint256. +// Uint256DecodeBytesBE attempts to decode the given string (in BE representation) into a Uint256. func Uint256DecodeBytesBE(b []byte) (u Uint256, err error) { if len(b) != Uint256Size { return u, fmt.Errorf("expected []byte of size %d got %d", Uint256Size, len(b)) @@ -54,7 +54,7 @@ func Uint256DecodeBytesBE(b []byte) (u Uint256, err error) { return u, nil } -// Uint256DecodeBytesLE attempts to decode the given string (in LE representation) into an Uint256. +// Uint256DecodeBytesLE attempts to decode the given string (in LE representation) into a Uint256. func Uint256DecodeBytesLE(b []byte) (u Uint256, err error) { b = slice.CopyReverse(b) return Uint256DecodeBytesBE(b) @@ -118,12 +118,12 @@ func (u Uint256) MarshalJSON() ([]byte, error) { // 0 implies u = other. func (u Uint256) CompareTo(other Uint256) int { return bytes.Compare(u[:], other[:]) } -// EncodeBinary implements io.Serializable interface. +// EncodeBinary implements the io.Serializable interface. func (u *Uint256) EncodeBinary(w *io.BinWriter) { w.WriteBytes(u[:]) } -// DecodeBinary implements io.Serializable interface. +// DecodeBinary implements the io.Serializable interface. func (u *Uint256) DecodeBinary(r *io.BinReader) { r.ReadBytes(u[:]) } diff --git a/pkg/vm/context.go b/pkg/vm/context.go index 8c0c2a1dc..c6440c9b6 100644 --- a/pkg/vm/context.go +++ b/pkg/vm/context.go @@ -48,9 +48,9 @@ type Context struct { // Call flags this context was created with. callFlag callflag.CallFlag - // retCount specifies number of return values. + // retCount specifies the number of return values. retCount int - // NEF represents NEF file for the current contract. + // NEF represents a NEF file for the current contract. NEF *nef.File // invTree is an invocation tree (or branch of it) for this context. invTree *InvocationTree @@ -78,19 +78,19 @@ func (c *Context) Estack() *Stack { return c.estack } -// NextIP returns next instruction pointer. +// NextIP returns the next instruction pointer. func (c *Context) NextIP() int { return c.nextip } -// Jump unconditionally moves the next instruction pointer to specified location. +// Jump unconditionally moves the next instruction pointer to the specified location. func (c *Context) Jump(pos int) { c.nextip = pos } // Next returns the next instruction to execute with its parameter if any. -// The parameter is not copied and shouldn't be written to. After its invocation -// the instruction pointer points to the instruction being returned. +// The parameter is not copied and shouldn't be written to. After its invocation, +// the instruction pointer points to the instruction returned. func (c *Context) Next() (opcode.Opcode, []byte, error) { var err error @@ -170,7 +170,7 @@ func (c *Context) Next() (opcode.Opcode, []byte, error) { return instr, parameter, nil } -// IP returns current instruction offset in the context script. +// IP returns the current instruction offset in the context script. func (c *Context) IP() int { return c.ip } @@ -201,7 +201,7 @@ func (c *Context) Copy() *Context { return ctx } -// GetCallFlags returns calling flags context was created with. +// GetCallFlags returns the calling flags which the context was created with. func (c *Context) GetCallFlags() callflag.CallFlag { return c.callFlag } @@ -219,38 +219,38 @@ func (c *Context) ScriptHash() util.Uint160 { return c.scriptHash } -// Value implements stackitem.Item interface. +// Value implements the stackitem.Item interface. func (c *Context) Value() interface{} { return c } -// Dup implements stackitem.Item interface. +// Dup implements the stackitem.Item interface. func (c *Context) Dup() stackitem.Item { return c } -// TryBool implements stackitem.Item interface. +// TryBool implements the stackitem.Item interface. func (c *Context) TryBool() (bool, error) { panic("can't convert Context to Bool") } -// TryBytes implements stackitem.Item interface. +// TryBytes implements the stackitem.Item interface. func (c *Context) TryBytes() ([]byte, error) { return nil, errors.New("can't convert Context to ByteArray") } -// TryInteger implements stackitem.Item interface. +// TryInteger implements the stackitem.Item interface. func (c *Context) TryInteger() (*big.Int, error) { return nil, errors.New("can't convert Context to Integer") } -// Type implements stackitem.Item interface. +// Type implements the stackitem.Item interface. func (c *Context) Type() stackitem.Type { panic("Context cannot appear on evaluation stack") } -// Convert implements stackitem.Item interface. +// Convert implements the stackitem.Item interface. func (c *Context) Convert(_ stackitem.Type) (stackitem.Item, error) { panic("Context cannot be converted to anything") } -// Equals implements stackitem.Item interface. +// Equals implements the stackitem.Item interface. func (c *Context) Equals(s stackitem.Item) bool { return c == s } @@ -268,7 +268,7 @@ func (c *Context) String() string { return "execution context" } -// IsDeployed returns whether this context contains deployed contract. +// IsDeployed returns whether this context contains a deployed contract. func (c *Context) IsDeployed() bool { return c.NEF != nil } @@ -309,8 +309,8 @@ func (v *VM) getContextScriptHash(n int) util.Uint160 { return ctx.ScriptHash() } -// PushContextScriptHash pushes to evaluation stack the script hash of the -// invocation stack element number n. +// PushContextScriptHash pushes the script hash of the +// invocation stack element number n to the evaluation stack. func (v *VM) PushContextScriptHash(n int) error { h := v.getContextScriptHash(n) v.Estack().PushItem(stackitem.NewByteArray(h.BytesBE())) diff --git a/pkg/vm/contract_checks.go b/pkg/vm/contract_checks.go index de5ebf51b..1336765f4 100644 --- a/pkg/vm/contract_checks.go +++ b/pkg/vm/contract_checks.go @@ -12,7 +12,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// MaxMultisigKeys is the maximum number of used keys for correct multisig contract. +// MaxMultisigKeys is the maximum number of keys allowed for correct multisig contract. const MaxMultisigKeys = 1024 var ( @@ -48,7 +48,7 @@ func IsMultiSigContract(script []byte) bool { return ok } -// ParseMultiSigContract returns number of signatures and list of public keys +// ParseMultiSigContract returns the number of signatures and a list of public keys // from the verification script of the contract. func ParseMultiSigContract(script []byte) (int, [][]byte, bool) { var nsigs, nkeys int @@ -111,8 +111,8 @@ func IsSignatureContract(script []byte) bool { return ok } -// ParseSignatureContract parses simple signature contract and returns -// public key. +// ParseSignatureContract parses a simple signature contract and returns +// a public key. func ParseSignatureContract(script []byte) ([]byte, bool) { if len(script) != 40 { return nil, false @@ -137,8 +137,8 @@ func IsStandardContract(script []byte) bool { return IsSignatureContract(script) || IsMultiSigContract(script) } -// IsScriptCorrect checks script for errors and mask provided for correctness wrt -// instruction boundaries. Normally it returns nil, but can return some specific +// IsScriptCorrect checks the script for errors and mask provided for correctness wrt +// instruction boundaries. Normally, it returns nil, but it can return some specific // error if there is any. func IsScriptCorrect(script []byte, methods bitfield.Field) error { var ( diff --git a/pkg/vm/emit/emit.go b/pkg/vm/emit/emit.go index 1a8450f3f..149cb25bd 100644 --- a/pkg/vm/emit/emit.go +++ b/pkg/vm/emit/emit.go @@ -29,7 +29,7 @@ func Opcodes(w *io.BinWriter, ops ...opcode.Opcode) { } } -// Bool emits a bool type the given buffer. +// Bool emits a bool type to the given buffer. func Bool(w *io.BinWriter, ok bool) { if ok { Opcodes(w, opcode.PUSHT) @@ -50,7 +50,7 @@ func padRight(s int, buf []byte) []byte { return buf } -// Int emits a int type to the given buffer. +// Int emits an int type to the given buffer. func Int(w *io.BinWriter, i int64) { if smallInt(w, i) { return @@ -58,7 +58,7 @@ func Int(w *io.BinWriter, i int64) { bigInt(w, big.NewInt(i), false) } -// BigInt emits big-integer to the given buffer. +// BigInt emits a big-integer to the given buffer. func BigInt(w *io.BinWriter, n *big.Int) { bigInt(w, n, true) } @@ -99,7 +99,7 @@ func bigInt(w *io.BinWriter, n *big.Int, trySmall bool) { w.WriteBytes(padRight(1<= 0 } -// HasFinally returns true iff context has `finally` block. +// HasFinally returns true iff the context has a `finally` block. func (c *exceptionHandlingContext) HasFinally() bool { return c.FinallyOffset >= 0 } -// String implements stackitem.Item interface. +// String implements the stackitem.Item interface. func (c *exceptionHandlingContext) String() string { return "exception handling context" } -// Value implements stackitem.Item interface. +// Value implements the stackitem.Item interface. func (c *exceptionHandlingContext) Value() interface{} { return c } -// Dup implements stackitem.Item interface. +// Dup implements the stackitem.Item interface. func (c *exceptionHandlingContext) Dup() stackitem.Item { return c } -// TryBool implements stackitem.Item interface. +// TryBool implements the stackitem.Item interface. func (c *exceptionHandlingContext) TryBool() (bool, error) { panic("can't convert exceptionHandlingContext to Bool") } -// TryBytes implements stackitem.Item interface. +// TryBytes implements the stackitem.Item interface. func (c *exceptionHandlingContext) TryBytes() ([]byte, error) { return nil, errors.New("can't convert exceptionHandlingContext to ByteArray") } -// TryInteger implements stackitem.Item interface. +// TryInteger implements the stackitem.Item interface. func (c *exceptionHandlingContext) TryInteger() (*big.Int, error) { return nil, errors.New("can't convert exceptionHandlingContext to Integer") } -// Type implements stackitem.Item interface. +// Type implements the stackitem.Item interface. func (c *exceptionHandlingContext) Type() stackitem.Type { panic("exceptionHandlingContext cannot appear on evaluation stack") } -// Convert implements stackitem.Item interface. +// Convert implements the stackitem.Item interface. func (c *exceptionHandlingContext) Convert(_ stackitem.Type) (stackitem.Item, error) { panic("exceptionHandlingContext cannot be converted to anything") } -// Equals implements stackitem.Item interface. +// Equals implements the stackitem.Item interface. func (c *exceptionHandlingContext) Equals(s stackitem.Item) bool { return c == s } diff --git a/pkg/vm/invocation_tree.go b/pkg/vm/invocation_tree.go index 8019bf467..c743310be 100644 --- a/pkg/vm/invocation_tree.go +++ b/pkg/vm/invocation_tree.go @@ -4,7 +4,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// InvocationTree represents a tree with script hashes, traversing it +// InvocationTree represents a tree with script hashes; when traversing it, // you can see how contracts called each other. type InvocationTree struct { Current util.Uint160 `json:"hash"` diff --git a/pkg/vm/opcode/from_string.go b/pkg/vm/opcode/from_string.go index b79d69ae9..79c0e3e44 100644 --- a/pkg/vm/opcode/from_string.go +++ b/pkg/vm/opcode/from_string.go @@ -11,7 +11,7 @@ func init() { } } -// FromString converts string representation to and opcode itself. +// FromString converts string representation to an opcode itself. func FromString(s string) (Opcode, error) { if op, ok := stringToOpcode[s]; ok { return op, nil diff --git a/pkg/vm/ref_counter.go b/pkg/vm/ref_counter.go index e3d787a0a..f119e3959 100644 --- a/pkg/vm/ref_counter.go +++ b/pkg/vm/ref_counter.go @@ -4,7 +4,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/stackitem" ) -// refCounter represents reference counter for the VM. +// refCounter represents a reference counter for the VM. type refCounter int type ( @@ -43,7 +43,7 @@ func (r *refCounter) Add(item stackitem.Item) { } } -// Remove removes item from the reference counter. +// Remove removes an item from the reference counter. func (r *refCounter) Remove(item stackitem.Item) { if r == nil { return diff --git a/pkg/vm/slot.go b/pkg/vm/slot.go index 132ee220c..69645f689 100644 --- a/pkg/vm/slot.go +++ b/pkg/vm/slot.go @@ -30,7 +30,7 @@ func (s slot) Set(i int, item stackitem.Item, refs *refCounter) { refs.Add(item) } -// Get returns item contained in i-th slot. +// Get returns the item contained in the i-th slot. func (s slot) Get(i int) stackitem.Item { if item := s[i]; item != nil { return item @@ -38,14 +38,14 @@ func (s slot) Get(i int) stackitem.Item { return stackitem.Null{} } -// Clear removes all slot variables from reference counter. +// Clear removes all slot variables from the reference counter. func (s slot) Clear(refs *refCounter) { for _, item := range s { refs.Remove(item) } } -// Size returns slot size. +// Size returns the slot size. func (s slot) Size() int { if s == nil { panic("not initialized") @@ -53,7 +53,7 @@ func (s slot) Size() int { return len(s) } -// MarshalJSON implements JSON marshalling interface. +// MarshalJSON implements the JSON marshalling interface. func (s slot) MarshalJSON() ([]byte, error) { arr := make([]json.RawMessage, len(s)) for i := range s { diff --git a/pkg/vm/stack.go b/pkg/vm/stack.go index a435ccbf4..503c25571 100644 --- a/pkg/vm/stack.go +++ b/pkg/vm/stack.go @@ -10,12 +10,12 @@ import ( ) // Stack implementation for the neo-go virtual machine. The stack with its LIFO -// semantics is emulated from simple slice where the top of the stack corresponds +// semantics is emulated from a simple slice, where the top of the stack corresponds // to the latest element of this slice. Pushes are appends to this slice, pops are // slice resizes. -// Element represents an element on the stack, technically it's a wrapper around -// stackitem.Item interface to provide some API simplification for VM. +// Element represents an element on the stack. Technically, it's a wrapper around +// stackitem.Item interface to provide some API simplification for the VM. type Element struct { value stackitem.Item } @@ -26,18 +26,18 @@ func NewElement(v interface{}) Element { return Element{stackitem.Make(v)} } -// Item returns Item contained in the element. +// Item returns the Item contained in the element. func (e Element) Item() stackitem.Item { return e.value } -// Value returns value of the Item contained in the element. +// Value returns the value of the Item contained in the element. func (e Element) Value() interface{} { return e.value.Value() } // BigInt attempts to get the underlying value of the element as a big integer. -// Will panic if the assertion failed which will be caught by the VM. +// It will panic if the assertion has failed, which will be caught by the VM. func (e Element) BigInt() *big.Int { val, err := e.value.TryInteger() if err != nil { @@ -46,8 +46,8 @@ func (e Element) BigInt() *big.Int { return val } -// Bool converts an underlying value of the element to a boolean if it's -// possible to do so, it will panic otherwise. +// Bool converts the underlying value of the element to a boolean if it's +// possible to do so. Otherwise, it will panic. func (e Element) Bool() bool { b, err := e.value.TryBool() if err != nil { @@ -57,7 +57,7 @@ func (e Element) Bool() bool { } // Bytes attempts to get the underlying value of the element as a byte array. -// Will panic if the assertion failed which will be caught by the VM. +// It will panic if the assertion has failed, which will be caught by the VM. func (e Element) Bytes() []byte { bs, err := e.value.TryBytes() if err != nil { @@ -67,7 +67,7 @@ func (e Element) Bytes() []byte { } // BytesOrNil attempts to get the underlying value of the element as a byte array or nil. -// Will panic if the assertion failed which will be caught by the VM. +// It will panic if the assertion has failed, which will be caught by the VM. func (e Element) BytesOrNil() []byte { if _, ok := e.value.(stackitem.Null); ok { return nil @@ -79,8 +79,8 @@ func (e Element) BytesOrNil() []byte { return bs } -// String attempts to get string from the element value. -// It is assumed to be use in interops and panics if string is not a valid UTF-8 byte sequence. +// String attempts to get a string from the element value. +// It is assumed to be used in interops and panics if the string is not a valid UTF-8 byte sequence. func (e Element) String() string { s, err := stackitem.ToString(e.value) if err != nil { @@ -90,7 +90,7 @@ func (e Element) String() string { } // Array attempts to get the underlying value of the element as an array of -// other items. Will panic if the item type is different which will be caught +// other items. It will panic if the item type is different, which will be caught // by the VM. func (e Element) Array() []stackitem.Item { switch t := e.value.(type) { @@ -170,7 +170,7 @@ func (s *Stack) Push(e Element) { s.refs.Add(e.value) } -// PushItem pushed an Item to the stack. +// PushItem pushes an Item to the stack. func (s *Stack) PushItem(i stackitem.Item) { s.Push(Element{i}) } @@ -181,7 +181,7 @@ func (s *Stack) PushVal(v interface{}) { s.Push(NewElement(v)) } -// Pop removes and returns the element on top of the stack. Panics if stack is +// Pop removes and returns the element on top of the stack. It panics if the stack is // empty. func (s *Stack) Pop() Element { l := len(s.elems) @@ -210,7 +210,7 @@ func (s *Stack) Back() Element { } // Peek returns the element (n) far in the stack beginning from -// the top of the stack. For n == 0 it's effectively the same as Top, +// the top of the stack. For n == 0 it's, effectively, the same as Top, // but it'll panic if the stack is empty. func (s *Stack) Peek(n int) Element { n = len(s.elems) - n - 1 @@ -218,7 +218,7 @@ func (s *Stack) Peek(n int) Element { } // RemoveAt removes the element (n) deep on the stack beginning -// from the top of the stack. Panics if called with out of bounds n. +// from the top of the stack. It panics if called with out of bounds n. func (s *Stack) RemoveAt(n int) Element { l := len(s.elems) e := s.elems[l-1-n] @@ -228,15 +228,15 @@ func (s *Stack) RemoveAt(n int) Element { } // Dup duplicates and returns the element at position n. -// Dup is used for copying elements on to the top of its own stack. -// s.Push(s.Peek(0)) // will result in unexpected behaviour. +// Dup is used for copying elements on the top of its own stack. +// s.Push(s.Peek(0)) // will result in unexpected behavior. // s.Push(s.Dup(0)) // is the correct approach. func (s *Stack) Dup(n int) Element { e := s.Peek(n) return Element{e.value.Dup()} } -// Iter iterates over all the elements int the stack, starting from the top +// Iter iterates over all elements int the stack, starting from the top // of the stack. // s.Iter(func(elem *Element) { // // do something with the element. @@ -247,7 +247,7 @@ func (s *Stack) Iter(f func(Element)) { } } -// IterBack iterates over all the elements of the stack, starting from the bottom +// IterBack iterates over all elements of the stack, starting from the bottom // of the stack. // s.IterBack(func(elem *Element) { // // do something with the element. @@ -288,8 +288,8 @@ func (s *Stack) ReverseTop(n int) error { return nil } -// Roll brings an item with the given index to the top of the stack, moving all -// the other elements down accordingly. It does all of that without popping and +// Roll brings an item with the given index to the top of the stack moving all +// other elements down accordingly. It does all of that without popping and // pushing elements. func (s *Stack) Roll(n int) error { if n < 0 { @@ -344,7 +344,7 @@ func (s *Stack) PopSigElements() ([][]byte, error) { return elems, nil } -// ToArray converts stack to an array of stackitems with top item being the last. +// ToArray converts the stack to an array of stackitems with the top item being the last. func (s *Stack) ToArray() []stackitem.Item { items := make([]stackitem.Item, 0, len(s.elems)) s.IterBack(func(e Element) { @@ -353,7 +353,7 @@ func (s *Stack) ToArray() []stackitem.Item { return items } -// MarshalJSON implements JSON marshalling interface. +// MarshalJSON implements the JSON marshalling interface. func (s *Stack) MarshalJSON() ([]byte, error) { items := s.ToArray() arr := make([]json.RawMessage, len(items)) diff --git a/pkg/vm/stackitem/item.go b/pkg/vm/stackitem/item.go index 10b921c5c..158b0cc5d 100644 --- a/pkg/vm/stackitem/item.go +++ b/pkg/vm/stackitem/item.go @@ -18,7 +18,7 @@ import ( ) const ( - // MaxBigIntegerSizeBits is the maximum size of BigInt item in bits. + // MaxBigIntegerSizeBits is the maximum size of a BigInt item in bits. MaxBigIntegerSizeBits = 32 * 8 // MaxSize is the maximum item size allowed in the VM. MaxSize = 1024 * 1024 @@ -26,10 +26,10 @@ const ( MaxComparableNumOfItems = MaxDeserialized // MaxClonableNumOfItems is the maximum number of items that can be cloned in structs. MaxClonableNumOfItems = MaxDeserialized - // MaxByteArrayComparableSize is the maximum allowed length of ByteArray for Equals method. + // MaxByteArrayComparableSize is the maximum allowed length of a ByteArray for Equals method. // It is set to be the maximum uint16 value. MaxByteArrayComparableSize = math.MaxUint16 - // MaxKeySize is the maximum size of map key. + // MaxKeySize is the maximum size of a map key. MaxKeySize = 64 ) @@ -61,13 +61,13 @@ type Convertible interface { } var ( - // ErrInvalidConversion is returned on attempt to make an incorrect + // ErrInvalidConversion is returned upon an attempt to make an incorrect // conversion between item types. ErrInvalidConversion = errors.New("invalid conversion") - // ErrTooBig is returned when item exceeds some size constraints like - // maximum allowed integer value of number of elements in array. It - // can also be returned by serialization functions if resulting + // ErrTooBig is returned when an item exceeds some size constraints, like + // the maximum allowed integer value of the number of elements in an array. It + // can also be returned by serialization functions if the resulting // value exceeds MaxSize. ErrTooBig = errors.New("too big") @@ -78,13 +78,13 @@ var ( errTooBigElements = fmt.Errorf("%w: many elements", ErrTooBig) ) -// mkInvConversion creates conversion error with additional metadata (from and +// mkInvConversion creates a conversion error with additional metadata (from and // to types). func mkInvConversion(from Item, to Type) error { return fmt.Errorf("%w: %s/%s", ErrInvalidConversion, from, to) } -// Make tries to make appropriate stack item from provided value. +// Make tries to make an appropriate stack item from the provided value. // It will panic if it's not possible. func Make(v interface{}) Item { switch val := v.(type) { @@ -136,7 +136,7 @@ func Make(v interface{}) Item { } } -// ToString converts Item to string if it is a valid UTF-8. +// ToString converts an Item to a string if it is a valid UTF-8. func ToString(item Item) (string, error) { bs, err := item.TryBytes() if err != nil { @@ -148,7 +148,7 @@ func ToString(item Item) (string, error) { return string(bs), nil } -// convertPrimitive converts primitive item to a specified type. +// convertPrimitive converts a primitive item to the specified type. func convertPrimitive(item Item, typ Type) (Item, error) { if item.Type() == typ { return item, nil @@ -187,64 +187,64 @@ type Struct struct { rc } -// NewStruct returns an new Struct object. +// NewStruct returns a new Struct object. func NewStruct(items []Item) *Struct { return &Struct{ value: items, } } -// Value implements Item interface. +// Value implements the Item interface. func (i *Struct) Value() interface{} { return i.value } -// Remove removes element at `pos` index from Struct value. -// It will panics on bad index. +// Remove removes the element at `pos` index from the Struct value. +// It will panic if a bad index given. func (i *Struct) Remove(pos int) { i.value = append(i.value[:pos], i.value[pos+1:]...) } -// Append adds Item at the end of Struct value. +// Append adds an Item to the end of the Struct value. func (i *Struct) Append(item Item) { i.value = append(i.value, item) } -// Clear removes all elements from Struct item value. +// Clear removes all elements from the Struct item value. func (i *Struct) Clear() { i.value = i.value[:0] } -// Len returns length of Struct value. +// Len returns the length of the Struct value. func (i *Struct) Len() int { return len(i.value) } -// String implements Item interface. +// String implements the Item interface. func (i *Struct) String() string { return "Struct" } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *Struct) Dup() Item { // it's a reference type, so no copying here. return i } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *Struct) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *Struct) TryBytes() ([]byte, error) { return nil, mkInvConversion(i, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *Struct) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *Struct) Equals(s Item) bool { if s == nil { return false @@ -281,10 +281,10 @@ func (i *Struct) equalStruct(s *Struct, limit *int) bool { return true } -// Type implements Item interface. +// Type implements the Item interface. func (i *Struct) Type() Type { return StructT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *Struct) Convert(typ Type) (Item, error) { switch typ { case StructT: @@ -300,7 +300,7 @@ func (i *Struct) Convert(typ Type) (Item, error) { } } -// Clone returns a Struct with all Struct fields copied by value. +// Clone returns a Struct with all Struct fields copied by the value. // Array fields are still copied by reference. func (i *Struct) Clone() (*Struct, error) { var limit = MaxClonableNumOfItems - 1 // For this struct itself. @@ -332,46 +332,46 @@ func (i *Struct) clone(limit *int) (*Struct, error) { // Null represents null on the stack. type Null struct{} -// String implements Item interface. +// String implements the Item interface. func (i Null) String() string { return "Null" } -// Value implements Item interface. +// Value implements the Item interface. func (i Null) Value() interface{} { return nil } -// Dup implements Item interface. -// There is no need to perform a real copy here, -// as Null has no internal state. +// Dup implements the Item interface. +// There is no need to perform a real copy here +// since Null has no internal state. func (i Null) Dup() Item { return i } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i Null) TryBool() (bool, error) { return false, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i Null) TryBytes() ([]byte, error) { return nil, mkInvConversion(i, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i Null) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i Null) Equals(s Item) bool { _, ok := s.(Null) return ok } -// Type implements Item interface. +// Type implements the Item interface. func (i Null) Type() Type { return AnyT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i Null) Convert(typ Type) (Item, error) { if typ == AnyT || !typ.IsValid() { return nil, mkInvConversion(i, typ) @@ -390,9 +390,9 @@ func NewBigInteger(value *big.Int) *BigInteger { return (*BigInteger)(value) } -// CheckIntegerSize checks that value size doesn't exceed VM limit for Interer. +// CheckIntegerSize checks that the value size doesn't exceed the VM limit for Interer. func CheckIntegerSize(value *big.Int) error { - // There are 2 cases, when `BitLen` differs from actual size: + // There are 2 cases when `BitLen` differs from the actual size: // 1. Positive integer with the highest bit on byte boundary = 1. // 2. Negative integer with the highest bit on byte boundary = 1 // minus some value. (-0x80 -> 0x80, -0x7F -> 0x81, -0x81 -> 0x7FFF). @@ -420,22 +420,22 @@ func (i *BigInteger) Bytes() []byte { return bigint.ToBytes(i.Big()) } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *BigInteger) TryBool() (bool, error) { return i.Big().Sign() != 0, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *BigInteger) TryBytes() ([]byte, error) { return i.Bytes(), nil } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *BigInteger) TryInteger() (*big.Int, error) { return i.Big(), nil } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *BigInteger) Equals(s Item) bool { if i == s { return true @@ -446,7 +446,7 @@ func (i *BigInteger) Equals(s Item) bool { return ok && i.Big().Cmp(val.Big()) == 0 } -// Value implements Item interface. +// Value implements the Item interface. func (i *BigInteger) Value() interface{} { return i.Big() } @@ -455,16 +455,16 @@ func (i *BigInteger) String() string { return "BigInteger" } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *BigInteger) Dup() Item { n := new(big.Int) return (*BigInteger)(n.Set(i.Big())) } -// Type implements Item interface. +// Type implements the Item interface. func (i *BigInteger) Type() Type { return IntegerT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *BigInteger) Convert(typ Type) (Item, error) { return convertPrimitive(i, typ) } @@ -482,7 +482,7 @@ func NewBool(val bool) Bool { return Bool(val) } -// Value implements Item interface. +// Value implements the Item interface. func (i Bool) Value() interface{} { return bool(i) } @@ -496,12 +496,12 @@ func (i Bool) String() string { return "Boolean" } -// Dup implements Item interface. +// Dup implements the Item interface. func (i Bool) Dup() Item { return i } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i Bool) TryBool() (bool, error) { return bool(i), nil } // Bytes converts Bool to bytes. @@ -512,12 +512,12 @@ func (i Bool) Bytes() []byte { return []byte{0} } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i Bool) TryBytes() ([]byte, error) { return i.Bytes(), nil } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i Bool) TryInteger() (*big.Int, error) { if i { return big.NewInt(1), nil @@ -525,7 +525,7 @@ func (i Bool) TryInteger() (*big.Int, error) { return big.NewInt(0), nil } -// Equals implements Item interface. +// Equals implements the Item interface. func (i Bool) Equals(s Item) bool { if i == s { return true @@ -536,10 +536,10 @@ func (i Bool) Equals(s Item) bool { return ok && i == val } -// Type implements Item interface. +// Type implements the Item interface. func (i Bool) Type() Type { return BooleanT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i Bool) Convert(typ Type) (Item, error) { return convertPrimitive(i, typ) } @@ -552,7 +552,7 @@ func NewByteArray(b []byte) *ByteArray { return (*ByteArray)(&b) } -// Value implements Item interface. +// Value implements the Item interface. func (i *ByteArray) Value() interface{} { return []byte(*i) } @@ -566,7 +566,7 @@ func (i *ByteArray) String() string { return "ByteString" } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *ByteArray) TryBool() (bool, error) { if len(*i) > MaxBigIntegerSizeBits/8 { return false, errTooBigInteger @@ -579,12 +579,12 @@ func (i *ByteArray) TryBool() (bool, error) { return false, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i ByteArray) TryBytes() ([]byte, error) { return i, nil } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i ByteArray) TryInteger() (*big.Int, error) { if len(i) > MaxBigIntegerSizeBits/8 { return nil, errTooBigInteger @@ -592,7 +592,7 @@ func (i ByteArray) TryInteger() (*big.Int, error) { return bigint.FromBytes(i), nil } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *ByteArray) Equals(s Item) bool { if len(*i) > MaxByteArrayComparableSize { panic(errTooBigComparable) @@ -612,16 +612,16 @@ func (i *ByteArray) Equals(s Item) bool { return bytes.Equal(*i, *val) } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *ByteArray) Dup() Item { ba := slice.Copy(*i) return (*ByteArray)(&ba) } -// Type implements Item interface. +// Type implements the Item interface. func (i *ByteArray) Type() Type { return ByteArrayT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *ByteArray) Convert(typ Type) (Item, error) { return convertPrimitive(i, typ) } @@ -639,23 +639,23 @@ func NewArray(items []Item) *Array { } } -// Value implements Item interface. +// Value implements the Item interface. func (i *Array) Value() interface{} { return i.value } -// Remove removes element at `pos` index from Array value. +// Remove removes the element at `pos` index from Array value. // It will panics on bad index. func (i *Array) Remove(pos int) { i.value = append(i.value[:pos], i.value[pos+1:]...) } -// Append adds Item at the end of Array value. +// Append adds an Item to the end of the Array value. func (i *Array) Append(item Item) { i.value = append(i.value, item) } -// Clear removes all elements from Array item value. +// Clear removes all elements from the Array item value. func (i *Array) Clear() { i.value = i.value[:0] } @@ -674,34 +674,34 @@ func (i *Array) String() string { return "Array" } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *Array) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *Array) TryBytes() ([]byte, error) { return nil, mkInvConversion(i, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *Array) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *Array) Equals(s Item) bool { return i == s } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *Array) Dup() Item { // reference type return i } -// Type implements Item interface. +// Type implements the Item interface. func (i *Array) Type() Type { return ArrayT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *Array) Convert(typ Type) (Item, error) { switch typ { case ArrayT: @@ -723,24 +723,24 @@ type MapElement struct { Value Item } -// Map represents Map object. It's ordered, so we use slice representation +// Map represents a Map object. It's ordered, so we use slice representation, // which should be fine for maps with less than 32 or so elements. Given that // our VM has quite low limit of overall stack items, it should be good enough, // but it can be extended with a real map for fast random access in the future -// if need be. +// if needed. type Map struct { value []MapElement rc } -// NewMap returns new Map object. +// NewMap returns a new Map object. func NewMap() *Map { return &Map{ value: make([]MapElement, 0), } } -// NewMapWithValue returns new Map object filled with specified value. +// NewMapWithValue returns a new Map object filled with the specified value. func NewMapWithValue(value []MapElement) *Map { if value != nil { return &Map{ @@ -750,35 +750,35 @@ func NewMapWithValue(value []MapElement) *Map { return NewMap() } -// Value implements Item interface. +// Value implements the Item interface. func (i *Map) Value() interface{} { return i.value } -// Clear removes all elements from Map item value. +// Clear removes all elements from the Map item value. func (i *Map) Clear() { i.value = i.value[:0] } -// Len returns length of Map value. +// Len returns the length of the Map value. func (i *Map) Len() int { return len(i.value) } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *Map) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *Map) TryBytes() ([]byte, error) { return nil, mkInvConversion(i, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *Map) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *Map) Equals(s Item) bool { return i == s } @@ -797,21 +797,21 @@ func (i *Map) Index(key Item) int { return -1 } -// Has checks if map has specified key. +// Has checks if the map has the specified key. func (i *Map) Has(key Item) bool { return i.Index(key) >= 0 } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *Map) Dup() Item { // reference type return i } -// Type implements Item interface. +// Type implements the Item interface. func (i *Map) Type() Type { return MapT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *Map) Convert(typ Type) (Item, error) { switch typ { case MapT: @@ -823,7 +823,7 @@ func (i *Map) Convert(typ Type) (Item, error) { } } -// Add adds key-value pair to the map. +// Add adds a key-value pair to the map. func (i *Map) Add(key, value Item) { if err := IsValidMapKey(key); err != nil { panic(err) @@ -836,13 +836,13 @@ func (i *Map) Add(key, value Item) { } } -// Drop removes given index from the map (no bounds check done here). +// Drop removes the given index from the map (no bounds check done here). func (i *Map) Drop(index int) { copy(i.value[index:], i.value[index+1:]) i.value = i.value[:len(i.value)-1] } -// IsValidMapKey checks whether it's possible to use given Item as a Map +// IsValidMapKey checks whether it's possible to use the given Item as a Map // key. func IsValidMapKey(key Item) error { switch key.(type) { @@ -864,14 +864,14 @@ type Interop struct { value interface{} } -// NewInterop returns new Interop object. +// NewInterop returns a new Interop object. func NewInterop(value interface{}) *Interop { return &Interop{ value: value, } } -// Value implements Item interface. +// Value implements the Item interface. func (i *Interop) Value() interface{} { return i.value } @@ -881,26 +881,26 @@ func (i *Interop) String() string { return "Interop" } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *Interop) Dup() Item { // reference type return i } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *Interop) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *Interop) TryBytes() ([]byte, error) { return nil, mkInvConversion(i, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *Interop) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *Interop) Equals(s Item) bool { if i == s { return true @@ -911,10 +911,10 @@ func (i *Interop) Equals(s Item) bool { return ok && i.value == val.value } -// Type implements Item interface. +// Type implements the Item interface. func (i *Interop) Type() Type { return InteropT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *Interop) Convert(typ Type) (Item, error) { switch typ { case InteropT: @@ -931,14 +931,14 @@ func (i *Interop) MarshalJSON() ([]byte, error) { return json.Marshal(i.value) } -// Pointer represents VM-level instruction pointer. +// Pointer represents a VM-level instruction pointer. type Pointer struct { pos int script []byte hash util.Uint160 } -// NewPointer returns new pointer on the specified position. +// NewPointer returns a new pointer on the specified position. func NewPointer(pos int, script []byte) *Pointer { return &Pointer{ pos: pos, @@ -947,9 +947,9 @@ func NewPointer(pos int, script []byte) *Pointer { } } -// NewPointerWithHash returns new pointer on the specified position of the +// NewPointerWithHash returns a new pointer on the specified position of the // specified script. It differs from NewPointer in that the script hash is being -// passed explicitly to save on hash calculcation. This hash is then being used +// passed explicitly to save on hash calculation. This hash is then being used // for pointer comparisons. func NewPointerWithHash(pos int, script []byte, h util.Uint160) *Pointer { return &Pointer{ @@ -959,17 +959,17 @@ func NewPointerWithHash(pos int, script []byte, h util.Uint160) *Pointer { } } -// String implements Item interface. +// String implements the Item interface. func (p *Pointer) String() string { return "Pointer" } -// Value implements Item interface. +// Value implements the Item interface. func (p *Pointer) Value() interface{} { return p.pos } -// Dup implements Item interface. +// Dup implements the Item interface. func (p *Pointer) Dup() Item { return &Pointer{ pos: p.pos, @@ -978,22 +978,22 @@ func (p *Pointer) Dup() Item { } } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (p *Pointer) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (p *Pointer) TryBytes() ([]byte, error) { return nil, mkInvConversion(p, ByteArrayT) } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (p *Pointer) TryInteger() (*big.Int, error) { return nil, mkInvConversion(p, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (p *Pointer) Equals(s Item) bool { if p == s { return true @@ -1002,12 +1002,12 @@ func (p *Pointer) Equals(s Item) bool { return ok && p.pos == ptr.pos && p.hash == ptr.hash } -// Type implements Item interface. +// Type implements the Item interface. func (p *Pointer) Type() Type { return PointerT } -// Convert implements Item interface. +// Convert implements the Item interface. func (p *Pointer) Convert(typ Type) (Item, error) { switch typ { case PointerT: @@ -1019,17 +1019,17 @@ func (p *Pointer) Convert(typ Type) (Item, error) { } } -// ScriptHash returns pointer item hash. +// ScriptHash returns the pointer item hash. func (p *Pointer) ScriptHash() util.Uint160 { return p.hash } -// Position returns pointer item position. +// Position returns the pointer item position. func (p *Pointer) Position() int { return p.pos } -// Buffer represents represents Buffer stack item. +// Buffer represents represents a Buffer stack item. type Buffer []byte // NewBuffer returns a new Buffer object. @@ -1037,37 +1037,37 @@ func NewBuffer(b []byte) *Buffer { return (*Buffer)(&b) } -// Value implements Item interface. +// Value implements the Item interface. func (i *Buffer) Value() interface{} { return []byte(*i) } -// String implements fmt.Stringer interface. +// String implements the fmt.Stringer interface. func (i *Buffer) String() string { return "Buffer" } -// TryBool implements Item interface. +// TryBool implements the Item interface. func (i *Buffer) TryBool() (bool, error) { return true, nil } -// TryBytes implements Item interface. +// TryBytes implements the Item interface. func (i *Buffer) TryBytes() ([]byte, error) { return *i, nil } -// TryInteger implements Item interface. +// TryInteger implements the Item interface. func (i *Buffer) TryInteger() (*big.Int, error) { return nil, mkInvConversion(i, IntegerT) } -// Equals implements Item interface. +// Equals implements the Item interface. func (i *Buffer) Equals(s Item) bool { return i == s } -// Dup implements Item interface. +// Dup implements the Item interface. func (i *Buffer) Dup() Item { return i } @@ -1077,10 +1077,10 @@ func (i *Buffer) MarshalJSON() ([]byte, error) { return json.Marshal(hex.EncodeToString(*i)) } -// Type implements Item interface. +// Type implements the Item interface. func (i *Buffer) Type() Type { return BufferT } -// Convert implements Item interface. +// Convert implements the Item interface. func (i *Buffer) Convert(typ Type) (Item, error) { switch typ { case BooleanT: @@ -1099,12 +1099,12 @@ func (i *Buffer) Convert(typ Type) (Item, error) { } } -// Len returns length of Buffer value. +// Len returns the length of the Buffer value. func (i *Buffer) Len() int { return len(*i) } -// DeepCopy returns new deep copy of the provided item. +// DeepCopy returns a new deep copy of the provided item. // Values of Interop items are not deeply copied. // It does preserve duplicates only for non-primitive types. func DeepCopy(item Item) Item { diff --git a/pkg/vm/stackitem/json.go b/pkg/vm/stackitem/json.go index a2da62657..12e9df816 100644 --- a/pkg/vm/stackitem/json.go +++ b/pkg/vm/stackitem/json.go @@ -12,7 +12,7 @@ import ( "strconv" ) -// decoder is a wrapper around json.Decoder helping to mimic C# json decoder behaviour. +// decoder is a wrapper around json.Decoder helping to mimic C# json decoder behavior. type decoder struct { json.Decoder @@ -23,10 +23,10 @@ type decoder struct { // MaxAllowedInteger is the maximum integer allowed to be encoded. const MaxAllowedInteger = 2<<53 - 1 -// MaxJSONDepth is the maximum allowed nesting level of encoded/decoded JSON. +// MaxJSONDepth is the maximum allowed nesting level of an encoded/decoded JSON. const MaxJSONDepth = 10 -// ErrInvalidValue is returned when item value doesn't fit some constraints +// ErrInvalidValue is returned when an item value doesn't fit some constraints // during serialization or deserialization. var ErrInvalidValue = errors.New("invalid value") @@ -47,8 +47,8 @@ func ToJSON(item Item) ([]byte, error) { return toJSON(nil, seen, item) } -// sliceNoPointer represents sub-slice of a known slice. -// It doesn't contain pointer and uses less memory than `[]byte`. +// sliceNoPointer represents a sub-slice of a known slice. +// It doesn't contain any pointer and uses less memory than `[]byte`. type sliceNoPointer struct { start, end int } @@ -138,8 +138,8 @@ func toJSON(data []byte, seen map[Item]sliceNoPointer, item Item) ([]byte, error return data, nil } -// itemToJSONString converts it to string -// surrounded in quotes with control characters escaped. +// itemToJSONString converts it to a string +// in quotation marks with control characters escaped. func itemToJSONString(it Item) ([]byte, error) { s, err := ToString(it) if err != nil { @@ -151,7 +151,7 @@ func itemToJSONString(it Item) ([]byte, error) { return bytes.Replace(data, []byte{'+'}, []byte("\\u002B"), -1), nil } -// FromJSON decodes Item from JSON. +// FromJSON decodes an Item from JSON. // It behaves as following: // string -> ByteArray from base64 // number -> BigInteger diff --git a/pkg/vm/stackitem/serialization.go b/pkg/vm/stackitem/serialization.go index 50c5a5f2e..fcc0c3c2b 100644 --- a/pkg/vm/stackitem/serialization.go +++ b/pkg/vm/stackitem/serialization.go @@ -13,17 +13,17 @@ import ( // (including itself). const MaxDeserialized = 2048 -// typicalNumOfItems is the number of items covering most serializaton needs. -// It's a hint used for map creation, so it's not limiting anything, it's just +// typicalNumOfItems is the number of items covering most serialization needs. +// It's a hint used for map creation, so it does not limit anything, it's just // a microoptimization to avoid excessive reallocations. Most of the serialized // items are structs, so there is at least one of them. const typicalNumOfItems = 4 -// ErrRecursive is returned on attempts to serialize some recursive stack item -// (like array including an item with reference to the same array). +// ErrRecursive is returned upon an attempt to serialize some recursive stack item +// (like an array including an item with the reference to the same array). var ErrRecursive = errors.New("recursive item") -// ErrUnserializable is returned on attempt to serialize some item that can't +// ErrUnserializable is returned upon an attempt to serialize some item that can't // be serialized (like Interop item or Pointer). var ErrUnserializable = errors.New("unserializable") @@ -42,7 +42,7 @@ type deserContext struct { limit int } -// Serialize encodes given Item into the byte slice. +// Serialize encodes the given Item into a byte slice. func Serialize(item Item) ([]byte, error) { sc := serContext{ allowInvalid: false, @@ -55,8 +55,8 @@ func Serialize(item Item) ([]byte, error) { return sc.data, nil } -// EncodeBinary encodes given Item into the given BinWriter. It's -// similar to io.Serializable's EncodeBinary, but works with Item +// EncodeBinary encodes the given Item into the given BinWriter. It's +// similar to io.Serializable's EncodeBinary but works with Item // interface. func EncodeBinary(item Item, w *io.BinWriter) { data, err := Serialize(item) @@ -67,11 +67,11 @@ func EncodeBinary(item Item, w *io.BinWriter) { w.WriteBytes(data) } -// EncodeBinaryProtected encodes given Item into the given BinWriter. It's +// EncodeBinaryProtected encodes the given Item into the given BinWriter. It's // similar to EncodeBinary but allows to encode interop items (only type, -// value is lost) and doesn't return any errors in w, instead if error -// (like recursive array) is encountered it just writes special InvalidT -// type of element to w. +// value is lost) and doesn't return any errors in the w. Instead, if an error +// (like recursive array) is encountered, it just writes the special InvalidT +// type of an element to the w. func EncodeBinaryProtected(item Item, w *io.BinWriter) { sc := serContext{ allowInvalid: true, @@ -185,7 +185,7 @@ func (w *serContext) appendVarUint(val uint64) { w.data = append(w.data, w.uv[:n]...) } -// Deserialize decodes Item from the given byte slice. +// Deserialize decodes the Item from the given byte slice. func Deserialize(data []byte) (Item, error) { r := io.NewBinReaderFromBuf(data) item := DecodeBinary(r) @@ -195,8 +195,8 @@ func Deserialize(data []byte) (Item, error) { return item, nil } -// DecodeBinary decodes previously serialized Item from the given -// reader. It's similar to the io.Serializable's DecodeBinary(), but implemented +// DecodeBinary decodes the previously serialized Item from the given +// reader. It's similar to the io.Serializable's DecodeBinary() but implemented // as a function because Item itself is an interface. Caveat: always check // reader's error value before using the returned Item. func DecodeBinary(r *io.BinReader) Item { diff --git a/pkg/vm/stackitem/type.go b/pkg/vm/stackitem/type.go index 30dee93fd..67f090e41 100644 --- a/pkg/vm/stackitem/type.go +++ b/pkg/vm/stackitem/type.go @@ -2,10 +2,10 @@ package stackitem import "errors" -// ErrInvalidType is returned on attempts to deserialize some unknown item type. +// ErrInvalidType is returned upon attempts to deserialize some unknown item type. var ErrInvalidType = errors.New("invalid type") -// Type represents type of the stack item. +// Type represents a type of the stack item. type Type byte // This block defines all known stack item types. @@ -23,7 +23,7 @@ const ( InvalidT Type = 0xFF ) -// String implements fmt.Stringer interface. +// String implements the fmt.Stringer interface. func (t Type) String() string { switch t { case AnyT: @@ -61,7 +61,7 @@ func (t Type) IsValid() bool { } } -// FromString returns stackitem type from string. +// FromString returns stackitem type from the string. func FromString(s string) (Type, error) { switch s { case "Any": diff --git a/pkg/vm/state.go b/pkg/vm/state.go index 8247a9dc5..64984b62b 100644 --- a/pkg/vm/state.go +++ b/pkg/vm/state.go @@ -44,7 +44,7 @@ func (s State) String() string { return strings.Join(ss, ", ") } -// StateFromString converts string into the VM State. +// StateFromString converts a string into the VM State. func StateFromString(s string) (st State, err error) { if s = strings.TrimSpace(s); s == "NONE" { return NoneState, nil diff --git a/pkg/vm/vm.go b/pkg/vm/vm.go index a7e29fffc..05fd2d1f2 100644 --- a/pkg/vm/vm.go +++ b/pkg/vm/vm.go @@ -39,7 +39,7 @@ func newError(ip int, op opcode.Opcode, err interface{}) *errorAtInstruct { return &errorAtInstruct{ip: ip, op: op, err: err} } -// StateMessage is a vm state message which could be used as additional info for example by cli. +// StateMessage is a vm state message which could be used as an additional info, for example by cli. type StateMessage string const ( @@ -122,18 +122,18 @@ func (v *VM) GasConsumed() int64 { return v.gasConsumed } -// AddGas consumes specified amount of gas. It returns true iff gas limit wasn't exceeded. +// AddGas consumes the specified amount of gas. It returns true if gas limit wasn't exceeded. func (v *VM) AddGas(gas int64) bool { v.gasConsumed += gas return v.GasLimit < 0 || v.gasConsumed <= v.GasLimit } -// Estack returns the evaluation stack so interop hooks can utilize this. +// Estack returns the evaluation stack, so interop hooks can utilize this. func (v *VM) Estack() *Stack { return v.estack } -// Istack returns the invocation stack so interop hooks can utilize this. +// Istack returns the invocation stack, so interop hooks can utilize this. func (v *VM) Istack() *Stack { return &v.istack } @@ -250,7 +250,7 @@ func (v *VM) EnableInvocationTree() { v.invTree = &InvocationTree{} } -// GetInvocationTree returns current invocation tree structure. +// GetInvocationTree returns the current invocation tree structure. func (v *VM) GetInvocationTree() *InvocationTree { return v.invTree } @@ -283,18 +283,18 @@ func (v *VM) LoadScriptWithFlags(b []byte, f callflag.CallFlag) { v.loadScriptWithCallingHash(b, nil, v.GetCurrentScriptHash(), util.Uint160{}, f, -1, 0) } -// LoadScriptWithHash if similar to the LoadScriptWithFlags method, but it also loads -// given script hash directly into the Context to avoid its recalculations and to make -// is possible to override it for deployed contracts with special hashes (the function +// LoadScriptWithHash is similar to the LoadScriptWithFlags method, but it also loads +// the given script hash directly into the Context to avoid its recalculations and to make +// it possible to override it for deployed contracts with special hashes (the function // assumes that it is used for deployed contracts setting context's parameters -// accordingly). It's up to user of this function to make sure the script and hash match +// accordingly). It's up to the user of this function to make sure the script and hash match // each other. func (v *VM) LoadScriptWithHash(b []byte, hash util.Uint160, f callflag.CallFlag) { v.loadScriptWithCallingHash(b, nil, v.GetCurrentScriptHash(), hash, f, 1, 0) } // LoadNEFMethod allows to create a context to execute a method from the NEF -// file with specified caller and executing hash, call flags, return value, +// file with the specified caller and executing hash, call flags, return value, // method and _initialize offsets. func (v *VM) LoadNEFMethod(exe *nef.File, caller util.Uint160, hash util.Uint160, f callflag.CallFlag, hasReturn bool, methodOff int, initOff int) { @@ -349,7 +349,7 @@ func (v *VM) Context() *Context { } // PopResult is used to pop the first item of the evaluation stack. This allows -// us to test compiler and vm in a bi-directional way. +// us to test the compiler and the vm in a bi-directional way. func (v *VM) PopResult() interface{} { if v.estack.Len() == 0 { return nil @@ -378,13 +378,13 @@ func (v *VM) State() State { return v.state } -// Ready returns true if the VM ready to execute the loaded program. -// Will return false if no program is loaded. +// Ready returns true if the VM is ready to execute the loaded program. +// It will return false if no program is loaded. func (v *VM) Ready() bool { return v.istack.Len() > 0 } -// Run starts the execution of the loaded program. +// Run starts execution of the loaded program. func (v *VM) Run() error { var ctx *Context @@ -432,7 +432,7 @@ func (v *VM) Step() error { return v.step(ctx) } -// step executes one instruction in given context. +// step executes one instruction in the given context. func (v *VM) step(ctx *Context) error { op, param, err := ctx.Next() if err != nil { @@ -442,7 +442,7 @@ func (v *VM) step(ctx *Context) error { return v.execute(ctx, op, param) } -// StepInto behaves the same as “step over” in case if the line does not contain a function. Otherwise +// StepInto behaves the same as “step over” in case the line does not contain a function. Otherwise, // the debugger will enter the called function and continue line-by-line debugging there. func (v *VM) StepInto() error { ctx := v.Context() @@ -491,8 +491,8 @@ func (v *VM) StepOut() error { return err } -// StepOver takes the debugger to the line that will step over a given line. -// If the line contains a function the function will be executed and the result returned without debugging each line. +// StepOver takes the debugger to the line that will step over the given line. +// If the line contains a function, the function will be executed and the result is returned without debugging each line. func (v *VM) StepOver() error { var err error if v.HasStopped() { @@ -518,23 +518,23 @@ func (v *VM) StepOver() error { return err } -// HasFailed returns whether VM is in the failed state now. Usually used to +// HasFailed returns whether the VM is in the failed state now. Usually, it's used to // check status after Run. func (v *VM) HasFailed() bool { return v.state.HasFlag(FaultState) } -// HasStopped returns whether VM is in Halt or Failed state. +// HasStopped returns whether the VM is in the Halt or Failed state. func (v *VM) HasStopped() bool { return v.state.HasFlag(HaltState) || v.state.HasFlag(FaultState) } -// HasHalted returns whether VM is in Halt state. +// HasHalted returns whether the VM is in the Halt state. func (v *VM) HasHalted() bool { return v.state.HasFlag(HaltState) } -// AtBreakpoint returns whether VM is at breakpoint. +// AtBreakpoint returns whether the VM is at breakpoint. func (v *VM) AtBreakpoint() bool { return v.state.HasFlag(BreakState) } @@ -1315,7 +1315,7 @@ func (v *VM) execute(ctx *Context, op opcode.Opcode, parameter []byte) (err erro case opcode.SIZE: elem := v.estack.Pop() var res int - // Cause there is no native (byte) item type here, hence we need to check + // Cause there is no native (byte) item type here, we need to check // the type of the item for array size operations. switch t := elem.Value().(type) { case []stackitem.Item: @@ -1348,7 +1348,7 @@ func (v *VM) execute(ctx *Context, op opcode.Opcode, parameter []byte) (err erro } case opcode.CALL, opcode.CALLL: - // Note: jump offset must be calculated regarding to new context, + // Note: jump offset must be calculated regarding the new context, // but it is cloned and thus has the same script and instruction pointer. v.call(ctx, getJumpOffset(ctx, parameter)) @@ -1579,13 +1579,13 @@ func (v *VM) throw(item stackitem.Item) { v.handleException() } -// Call calls method by offset using new execution context. +// Call calls a method by offset using the new execution context. func (v *VM) Call(offset int) { v.call(v.Context(), offset) } // call is an internal representation of Call, which does not -// affect the invocation counter and is only being used by vm +// affect the invocation counter and is only used by vm // package. func (v *VM) call(ctx *Context, offset int) { v.checkInvocationStackSize() @@ -1594,7 +1594,7 @@ func (v *VM) call(ctx *Context, offset int) { newCtx.local = nil newCtx.arguments = nil // If memory for `elems` is reused, we can end up - // with incorrect exception context state in the caller. + // with an incorrect exception context state in the caller. newCtx.tryStack.elems = nil initStack(&newCtx.tryStack, "exception", nil) newCtx.NEF = ctx.NEF @@ -1602,8 +1602,8 @@ func (v *VM) call(ctx *Context, offset int) { newCtx.Jump(offset) } -// getJumpOffset returns instruction number in a current context -// to a which JMP should be performed. +// getJumpOffset returns an instruction number in the current context +// to which JMP should be performed. // parameter should have length either 1 or 4 and // is interpreted as little-endian. func getJumpOffset(ctx *Context, parameter []byte) int { @@ -1614,8 +1614,8 @@ func getJumpOffset(ctx *Context, parameter []byte) int { return offset } -// calcJumpOffset returns absolute and relative offset of JMP/CALL/TRY instructions -// either in short (1-byte) or long (4-byte) form. +// calcJumpOffset returns an absolute and a relative offset of JMP/CALL/TRY instructions +// either in a short (1-byte) or a long (4-byte) form. func calcJumpOffset(ctx *Context, parameter []byte) (int, int, error) { var rOffset int32 switch l := len(parameter); l { @@ -1666,7 +1666,7 @@ func (v *VM) handleException() { throwUnhandledException(v.uncaughtException) } -// throwUnhandledException gets exception message from the provided stackitem and panics. +// throwUnhandledException gets an exception message from the provided stackitem and panics. func throwUnhandledException(item stackitem.Item) { msg := "unhandled exception" switch item.Type() { @@ -1686,7 +1686,7 @@ func throwUnhandledException(item stackitem.Item) { panic(msg) } -// CheckMultisigPar checks if sigs contains sufficient valid signatures. +// CheckMultisigPar checks if the sigs contains sufficient valid signatures. func CheckMultisigPar(v *VM, curve elliptic.Curve, h []byte, pkeys [][]byte, sigs [][]byte) bool { if len(sigs) == 1 { return checkMultisig1(v, curve, h, pkeys, sigs[0]) @@ -1849,17 +1849,17 @@ func bytesToPublicKey(b []byte, curve elliptic.Curve) *keys.PublicKey { return pkey } -// GetCallingScriptHash implements ScriptHashGetter interface. +// GetCallingScriptHash implements the ScriptHashGetter interface. func (v *VM) GetCallingScriptHash() util.Uint160 { return v.Context().callingScriptHash } -// GetEntryScriptHash implements ScriptHashGetter interface. +// GetEntryScriptHash implements the ScriptHashGetter interface. func (v *VM) GetEntryScriptHash() util.Uint160 { return v.getContextScriptHash(v.istack.Len() - 1) } -// GetCurrentScriptHash implements ScriptHashGetter interface. +// GetCurrentScriptHash implements the ScriptHashGetter interface. func (v *VM) GetCurrentScriptHash() util.Uint160 { return v.getContextScriptHash(0) } diff --git a/pkg/wallet/account.go b/pkg/wallet/account.go index 160bc63b2..bc370eb23 100644 --- a/pkg/wallet/account.go +++ b/pkg/wallet/account.go @@ -15,7 +15,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/vm/opcode" ) -// Account represents a NEO account. It holds the private and public key +// Account represents a NEO account. It holds the private and the public key // along with some metadata. type Account struct { // NEO private key. diff --git a/pkg/wallet/token.go b/pkg/wallet/token.go index ecea33f93..8fc87ea47 100644 --- a/pkg/wallet/token.go +++ b/pkg/wallet/token.go @@ -5,7 +5,7 @@ import ( "github.com/nspcc-dev/neo-go/pkg/util" ) -// Token represents imported token contract. +// Token represents an imported token contract. type Token struct { Name string `json:"name"` Hash util.Uint160 `json:"script_hash"` @@ -14,7 +14,7 @@ type Token struct { Standard string `json:"standard"` } -// NewToken returns new token contract info. +// NewToken returns the new token contract info. func NewToken(tokenHash util.Uint160, name, symbol string, decimals int64, standardName string) *Token { return &Token{ Name: name, diff --git a/pkg/wallet/wallet.go b/pkg/wallet/wallet.go index bf89300e9..f15c8a1c6 100644 --- a/pkg/wallet/wallet.go +++ b/pkg/wallet/wallet.go @@ -115,12 +115,12 @@ func (w *Wallet) RemoveAccount(addr string) error { return errors.New("account wasn't found") } -// AddToken adds new token to a wallet. +// AddToken adds a new token to a wallet. func (w *Wallet) AddToken(tok *Token) { w.Extra.Tokens = append(w.Extra.Tokens, tok) } -// RemoveToken removes token with the specified hash from the wallet. +// RemoveToken removes the token with the specified hash from the wallet. func (w *Wallet) RemoveToken(h util.Uint160) error { for i, tok := range w.Extra.Tokens { if tok.Hash.Equals(h) { @@ -149,7 +149,7 @@ func (w *Wallet) Save() error { return w.writeRaw(data) } -// savePretty saves wallet in a beautiful JSON. +// savePretty saves the wallet in a beautiful JSON. func (w *Wallet) savePretty() error { data, err := json.MarshalIndent(w, "", " ") if err != nil { @@ -172,7 +172,7 @@ func (w *Wallet) JSON() ([]byte, error) { func (w *Wallet) Close() { } -// GetAccount returns account corresponding to the provided scripthash. +// GetAccount returns an account corresponding to the provided scripthash. func (w *Wallet) GetAccount(h util.Uint160) *Account { addr := address.Uint160ToString(h) for _, acc := range w.Accounts {