fix spelling and godoc comments

This commit is contained in:
Vsevolod Brekelov 2019-10-22 17:56:03 +03:00
parent f1750d117b
commit 8ee421db14
63 changed files with 179 additions and 179 deletions

View file

@ -130,7 +130,7 @@ func (s *AccountState) EncodeBinary(bw *io.BinWriter) {
}
}
// Returns only the non-zero balances for the account.
// nonZeroBalances returns only the non-zero balances for the account.
func (s *AccountState) nonZeroBalances() map[util.Uint256]util.Fixed8 {
b := make(map[util.Uint256]util.Fixed8)
for k, v := range s.Balances {

View file

@ -39,7 +39,7 @@ func merkleTreeFromTransactions(txes []*transaction.Transaction) (*crypto.Merkle
return crypto.NewMerkleTree(hashes)
}
// rebuildMerkleRoot rebuild the merkleroot of the block.
// rebuildMerkleRoot rebuilds the merkleroot of the block.
func (b *Block) rebuildMerkleRoot() error {
merkle, err := merkleTreeFromTransactions(b.Transactions)
if err != nil {
@ -50,7 +50,7 @@ func (b *Block) rebuildMerkleRoot() error {
return nil
}
// Verify the integrity of the block.
// Verify verifies the integrity of the block.
func (b *Block) Verify() error {
// There has to be some transaction inside.
if len(b.Transactions) == 0 {

View file

@ -53,7 +53,7 @@ func (b *BlockBase) Verify() bool {
return true
}
// Hash return the hash of the block.
// Hash returns the hash of the block.
func (b *BlockBase) Hash() util.Uint256 {
if b.hash.Equals(util.Uint256{}) {
b.createHash()
@ -132,7 +132,7 @@ func (b *BlockBase) encodeHashableFields(bw *io.BinWriter) {
bw.WriteLE(b.NextConsensus)
}
// decodeHashableFields will only decode the fields used for hashing.
// decodeHashableFields decodes the fields used for hashing.
// see Hash() for more information about the fields.
func (b *BlockBase) decodeHashableFields(br *io.BinReader) {
br.ReadLE(&b.Version)

View file

@ -20,7 +20,7 @@ import (
log "github.com/sirupsen/logrus"
)
// tuning parameters
// Tuning parameters.
const (
headerBatchCount = 2000
version = "0.0.1"
@ -57,7 +57,7 @@ type Blockchain struct {
// Number of headers stored in the chain file.
storedHeaderCount uint32
// All operation on headerList must be called from an
// All operations on headerList must be called from an
// headersOp to be routine safe.
headerList *HeaderHashList
@ -70,7 +70,7 @@ type Blockchain struct {
type headersOpFunc func(headerList *HeaderHashList)
// NewBlockchain return a new blockchain object the will use the
// NewBlockchain returns a new blockchain object the will use the
// given Store as its underlying storage.
func NewBlockchain(s storage.Store, cfg config.ProtocolConfiguration) (*Blockchain, error) {
bc := &Blockchain{
@ -235,7 +235,7 @@ func (bc *Blockchain) AddBlock(block *Block) error {
return bc.storeBlock(block)
}
// AddHeaders will process the given headers and add them to the
// AddHeaders processes the given headers and add them to the
// HeaderHashList.
func (bc *Blockchain) AddHeaders(headers ...*Header) (err error) {
var (
@ -622,7 +622,7 @@ func getHeaderFromStore(s storage.Store, hash util.Uint256) (*Header, error) {
return block.Header(), nil
}
// HasTransaction return true if the blockchain contains he given
// HasTransaction returns true if the blockchain contains he given
// transaction hash.
func (bc *Blockchain) HasTransaction(hash util.Uint256) bool {
return bc.memPool.ContainsKey(hash) ||
@ -639,7 +639,7 @@ func checkTransactionInStore(s storage.Store, hash util.Uint256) bool {
return false
}
// HasBlock return true if the blockchain contains the given
// HasBlock returns true if the blockchain contains the given
// block hash.
func (bc *Blockchain) HasBlock(hash util.Uint256) bool {
if header, err := bc.GetHeader(hash); err == nil {
@ -666,7 +666,7 @@ func (bc *Blockchain) CurrentHeaderHash() (hash util.Uint256) {
return
}
// GetHeaderHash return the hash from the headerList by its
// GetHeaderHash returns the hash from the headerList by its
// height/index.
func (bc *Blockchain) GetHeaderHash(i int) (hash util.Uint256) {
bc.headersOp <- func(headerList *HeaderHashList) {
@ -686,7 +686,7 @@ func (bc *Blockchain) HeaderHeight() uint32 {
return uint32(bc.headerListLen() - 1)
}
// GetAssetState returns asset state from its assetID
// GetAssetState returns asset state from its assetID.
func (bc *Blockchain) GetAssetState(assetID util.Uint256) *AssetState {
return getAssetStateFromStore(bc.store, assetID)
}
@ -732,7 +732,7 @@ func getContractStateFromStore(s storage.Store, hash util.Uint160) *ContractStat
return &c
}
// GetAccountState returns the account state from its script hash
// GetAccountState returns the account state from its script hash.
func (bc *Blockchain) GetAccountState(scriptHash util.Uint160) *AccountState {
as, err := getAccountStateFromStore(bc.store, scriptHash)
if as == nil && err != storage.ErrKeyNotFound {
@ -750,7 +750,7 @@ func (bc *Blockchain) GetUnspentCoinState(hash util.Uint256) *UnspentCoinState {
return ucs
}
// GetConfig returns the config stored in the blockchain
// GetConfig returns the config stored in the blockchain.
func (bc *Blockchain) GetConfig() config.ProtocolConfiguration {
return bc.config
}
@ -777,12 +777,12 @@ func (bc *Blockchain) References(t *transaction.Transaction) map[transaction.Inp
return references
}
// FeePerByte returns network fee divided by the size of the transaction
// FeePerByte returns network fee divided by the size of the transaction.
func (bc *Blockchain) FeePerByte(t *transaction.Transaction) util.Fixed8 {
return bc.NetworkFee(t).Div(int64(io.GetVarSize(t)))
}
// NetworkFee returns network fee
// NetworkFee returns network fee.
func (bc *Blockchain) NetworkFee(t *transaction.Transaction) util.Fixed8 {
inputAmount := util.Fixed8FromInt64(0)
for _, txOutput := range bc.References(t) {
@ -801,13 +801,13 @@ func (bc *Blockchain) NetworkFee(t *transaction.Transaction) util.Fixed8 {
return inputAmount.Sub(outputAmount).Sub(bc.SystemFee(t))
}
// SystemFee returns system fee
// SystemFee returns system fee.
func (bc *Blockchain) SystemFee(t *transaction.Transaction) util.Fixed8 {
return bc.GetConfig().SystemFee.TryGetValue(t.Type)
}
// IsLowPriority flags a trnsaction as low priority if the network fee is less than
// LowPriorityThreshold
// IsLowPriority flags a transaction as low priority if the network fee is less than
// LowPriorityThreshold.
func (bc *Blockchain) IsLowPriority(t *transaction.Transaction) bool {
return bc.NetworkFee(t) < util.Fixed8FromFloat(bc.GetConfig().LowPriorityThreshold)
}
@ -1135,13 +1135,13 @@ func (bc *Blockchain) verifyHashAgainstScript(hash util.Uint160, witness *transa
return nil
}
// verifyTxWitnesses verify the scripts (witnesses) that come with a given
// verifyTxWitnesses verifies the scripts (witnesses) that come with a given
// transaction. It can reorder them by ScriptHash, because that's required to
// match a slice of script hashes from the Blockchain. Block parameter
// is used for easy interop access and can be omitted for transactions that are
// not yet added into any block.
// Golang implementation of VerifyWitnesses method in C# (https://github.com/neo-project/neo/blob/master/neo/SmartContract/Helper.cs#L87).
// Unfortunately the IVerifiable interface could not be implemented because we can't move the References method in blockchain.go to the transaction.go file
// Unfortunately the IVerifiable interface could not be implemented because we can't move the References method in blockchain.go to the transaction.go file.
func (bc *Blockchain) verifyTxWitnesses(t *transaction.Transaction, block *Block) error {
hashes, err := bc.GetScriptHashesForVerifying(t)
if err != nil {

View file

@ -10,7 +10,7 @@ import (
type Header struct {
// Base of the block.
BlockBase
// Padding that is fixed to 0
// Padding that is fixed to 0.
_ uint8
}
@ -26,7 +26,7 @@ func (h *Header) DecodeBinary(r *io.BinReader) {
}
}
// EncodeBinary implements Serializable interface.
// EncodeBinary implements Serializable interface.
func (h *Header) EncodeBinary(w *io.BinWriter) {
h.BlockBase.EncodeBinary(w)
w.WriteLE(uint8(0))

View file

@ -6,18 +6,18 @@ import (
)
// A HeaderHashList represents a list of header hashes.
// This datastructure in not routine safe and should be
// This data structure in not routine safe and should be
// used under some kind of protection against race conditions.
type HeaderHashList struct {
hashes []util.Uint256
}
// NewHeaderHashListFromBytes return a new hash list from the given bytes.
// NewHeaderHashListFromBytes returns a new hash list from the given bytes.
func NewHeaderHashListFromBytes(b []byte) (*HeaderHashList, error) {
return nil, nil
}
// NewHeaderHashList return a new pointer to a HeaderHashList.
// NewHeaderHashList returns a new pointer to a HeaderHashList.
func NewHeaderHashList(hashes ...util.Uint256) *HeaderHashList {
return &HeaderHashList{
hashes: hashes,
@ -29,7 +29,7 @@ func (l *HeaderHashList) Add(h ...util.Uint256) {
l.hashes = append(l.hashes, h...)
}
// Len return the length of the underlying hashes slice.
// Len returns the length of the underlying hashes slice.
func (l *HeaderHashList) Len() int {
return len(l.hashes)
}
@ -55,7 +55,7 @@ func (l *HeaderHashList) Slice(start, end int) []util.Uint256 {
return l.hashes[start:end]
}
// WriteTo will write n underlying hashes to the given BinWriter
// WriteTo writes n underlying hashes to the given BinWriter
// starting from start.
func (l *HeaderHashList) Write(bw *io.BinWriter, start, n int) error {
bw.WriteVarUint(uint64(n))

View file

@ -316,7 +316,7 @@ func (ic *interopContext) checkKeyedWitness(key *keys.PublicKey) (bool, error) {
return ic.checkHashedWitness(hash.Hash160(script))
}
// runtimeCheckWitness should check witnesses.
// runtimeCheckWitness checks witnesses.
func (ic *interopContext) runtimeCheckWitness(v *vm.VM) error {
var res bool
var err error
@ -348,7 +348,7 @@ func (ic *interopContext) runtimeNotify(v *vm.VM) error {
return nil
}
// runtimeLog log the message passed.
// runtimeLog logs the message passed.
func (ic *interopContext) runtimeLog(v *vm.VM) error {
msg := fmt.Sprintf("%q", v.Estack().Pop().Bytes())
log.Infof("script %s logs: %s", getContextScriptHash(v, 0), msg)
@ -373,12 +373,12 @@ func (ic *interopContext) runtimeGetTime(v *vm.VM) error {
}
/*
// runtimeSerialize should serialize given stack item.
// runtimeSerialize serializes given stack item.
func (ic *interopContext) runtimeSerialize(v *vm.VM) error {
panic("TODO")
}
// runtimeDeserialize should deserialize given stack item.
// runtimeDeserialize deserializes given stack item.
func (ic *interopContext) runtimeDeserialize(v *vm.VM) error {
panic("TODO")
}

View file

@ -16,7 +16,7 @@ type PoolItem struct {
fee Feer
}
// PoolItems slice of PoolItem
// PoolItems slice of PoolItem.
type PoolItems []*PoolItem
// MemPool stores the unconfirms transactions.
@ -59,7 +59,7 @@ func (p PoolItem) CompareTo(otherP *PoolItem) int {
}
}
// Fees sorted ascending
// Fees sorted ascending.
pFPB := p.fee.FeePerByte(p.txn)
otherFPB := p.fee.FeePerByte(otherP.txn)
if ret := pFPB.CompareTo(otherFPB); ret != 0 {
@ -72,7 +72,7 @@ func (p PoolItem) CompareTo(otherP *PoolItem) int {
return ret
}
// Transaction hash sorted descending
// Transaction hash sorted descending.
return otherP.txn.Hash().CompareTo(p.txn.Hash())
}
@ -187,7 +187,7 @@ func NewMemPool(capacity int) MemPool {
}
}
// TryGetValue returns a transactions if it esists in the memory pool.
// TryGetValue returns a transaction if it exists in the memory pool.
func (mp MemPool) TryGetValue(hash util.Uint256) (*transaction.Transaction, bool) {
mp.lock.Lock()
defer mp.lock.Unlock()
@ -220,8 +220,8 @@ func getLowestFeeTransaction(verifiedTxnSorted PoolItems, unverifiedTxnSorted Po
}
// min return the minimum item in a ascending sorted slice of pool items.
// The function can't be applied to unsorted slice!
// min returns the minimum item in a ascending sorted slice of pool items.
// The function can't be applied to unsorted slice!
func min(sortedPool PoolItems) *PoolItem {
if len(sortedPool) == 0 {
return nil

View file

@ -9,14 +9,14 @@ import (
"github.com/CityOfZion/neo-go/pkg/util"
)
// Version will attempt to get the current version stored in the
// Version attempts to get the current version stored in the
// underlying Store.
func Version(s Store) (string, error) {
version, err := s.Get(SYSVersion.Bytes())
return string(version), err
}
// PutVersion will store the given version in the underlying Store.
// PutVersion stores the given version in the underlying Store.
func PutVersion(s Store, v string) error {
return s.Put(SYSVersion.Bytes(), []byte(v))
}

View file

@ -18,7 +18,7 @@ type LevelDBStore struct {
path string
}
// NewLevelDBStore return a new LevelDBStore object that will
// NewLevelDBStore returns a new LevelDBStore object that will
// initialize the database found at the given path.
func NewLevelDBStore(cfg LevelDBOptions) (*LevelDBStore, error) {
var opts *opt.Options // should be exposed via LevelDBOptions if anything needed

View file

@ -14,7 +14,7 @@ type MemoryStore struct {
del map[string]bool
}
// MemoryBatch a in-memory batch compatible with MemoryStore.
// MemoryBatch is an in-memory batch compatible with MemoryStore.
type MemoryBatch struct {
MemoryStore
}
@ -65,7 +65,7 @@ func (s *MemoryStore) Put(key, value []byte) error {
return nil
}
// drop deletes a key-valu pair from the store, it's supposed to be called
// drop deletes a key-value pair from the store, it's supposed to be called
// with mutex locked.
func (s *MemoryStore) drop(key string) {
s.del[key] = true

View file

@ -58,8 +58,8 @@ func (k KeyPrefix) Bytes() []byte {
return []byte{byte(k)}
}
// AppendPrefix append byteslice b to the given KeyPrefix.
// AppendKeyPrefix(SYSVersion, []byte{0x00, 0x01})
// AppendPrefix appends byteslice b to the given KeyPrefix.
// AppendKeyPrefix(SYSVersion, []byte{0x00, 0x01})
func AppendPrefix(k KeyPrefix, b []byte) []byte {
dest := make([]byte, len(b)+1)
dest[0] = byte(k)
@ -68,7 +68,7 @@ func AppendPrefix(k KeyPrefix, b []byte) []byte {
}
// AppendPrefixInt append int n to the given KeyPrefix.
// AppendPrefixInt(SYSCurrentHeader, 10001)
//AppendPrefixInt(SYSCurrentHeader, 10001)
func AppendPrefixInt(k KeyPrefix, n int) []byte {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, uint32(n))

View file

@ -1,6 +1,6 @@
package transaction
// AssetType represent a NEO asset type
// AssetType represents a NEO asset type.
type AssetType uint8
// Valid asset types.

View file

@ -72,7 +72,7 @@ func (attr *Attribute) EncodeBinary(bw *io.BinWriter) {
}
}
// MarshalJSON implements the json Marschaller interface
// MarshalJSON implements the json Marshaller interface.
func (attr *Attribute) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]string{
"usage": attr.Usage.String(),

View file

@ -11,7 +11,7 @@ import (
// and send a deposit to the address of the PublicKey.
// The way to cancel the registration is: Spend the deposit on the address of the PublicKey.
type EnrollmentTX struct {
// PublicKey of the validator
// PublicKey of the validator.
PublicKey *keys.PublicKey
}

View file

@ -20,7 +20,7 @@ type Output struct {
ScriptHash util.Uint160
// The position of the Output in slice []Output. This is actually set in NewTransactionOutputRaw
// and used for diplaying purposes.
// and used for displaying purposes.
Position int
}
@ -47,7 +47,7 @@ func (out *Output) EncodeBinary(bw *io.BinWriter) {
bw.WriteLE(out.ScriptHash)
}
// MarshalJSON implements the Marshaler interface
// MarshalJSON implements the Marshaler interface.
func (out *Output) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"asset": out.AssetID,

View file

@ -15,14 +15,14 @@ type RegisterTX struct {
// Name of the asset being registered.
Name string
// Amount registered
// Unlimited mode -0.00000001
// Amount registered.
// Unlimited mode -0.00000001.
Amount util.Fixed8
// Decimals
// Decimals.
Precision uint8
// Public key of the owner
// Public key of the owner.
Owner *keys.PublicKey
Admin util.Uint160

View file

@ -59,7 +59,7 @@ func NewTrimmedTX(hash util.Uint256) *Transaction {
}
}
// Hash return the hash of the transaction.
// Hash returns the hash of the transaction.
func (t *Transaction) Hash() util.Uint256 {
if t.hash.Equals(util.Uint256{}) {
if t.createHash() != nil {
@ -173,7 +173,7 @@ func (t *Transaction) EncodeBinary(bw *io.BinWriter) {
}
}
// encodeHashableFields will only encode the fields that are not used for
// encodeHashableFields encodes the fields that are not used for
// signing the transaction, which are all fields except the scripts.
func (t *Transaction) encodeHashableFields(bw *io.BinWriter) {
bw.WriteLE(t.Type)
@ -236,7 +236,7 @@ func (t Transaction) GroupOutputByAssetID() map[util.Uint256][]*Output {
return m
}
// Bytes convert the transaction to []byte
// Bytes converts the transaction to []byte
func (t *Transaction) Bytes() []byte {
buf := io.NewBufBinWriter()
t.EncodeBinary(buf.BinWriter)

View file

@ -14,7 +14,7 @@ import (
"github.com/CityOfZion/neo-go/pkg/vm"
)
// Creates a genesis block based on the given configuration.
// createGenesisBlock creates a genesis block based on the given configuration.
func createGenesisBlock(cfg config.ProtocolConfiguration) (*Block, error) {
validators, err := getValidators(cfg)
if err != nil {

View file

@ -8,13 +8,13 @@ import (
)
// Sha256 hashes the incoming byte slice
// using the sha256 algorithm
// using the sha256 algorithm.
func Sha256(data []byte) util.Uint256 {
hash := sha256.Sum256(data)
return hash
}
// DoubleSha256 performs sha256 twice on the given data
// DoubleSha256 performs sha256 twice on the given data.
func DoubleSha256(data []byte) util.Uint256 {
var hash util.Uint256
@ -24,7 +24,7 @@ func DoubleSha256(data []byte) util.Uint256 {
}
// RipeMD160 performs the RIPEMD160 hash algorithm
// on the given data
// on the given data.
func RipeMD160(data []byte) util.Uint160 {
var hash util.Uint160
hasher := ripemd160.New()
@ -35,7 +35,7 @@ func RipeMD160(data []byte) util.Uint160 {
}
// Hash160 performs sha256 and then ripemd160
// on the given data
// on the given data.
func Hash160(data []byte) util.Uint160 {
var hash util.Uint160
@ -47,7 +47,7 @@ func Hash160(data []byte) util.Uint160 {
}
// Checksum returns the checksum for a given piece of data
// using sha256 twice as the hash algorithm
// using sha256 twice as the hash algorithm.
func Checksum(data []byte) []byte {
hash := DoubleSha256(data)
return hash[:4]

View file

@ -41,7 +41,7 @@ type PublicKey struct {
Y *big.Int
}
// NewPublicKeyFromString return a public key created from the
// NewPublicKeyFromString returns a public key created from the
// given hex string.
func NewPublicKeyFromString(s string) (*PublicKey, error) {
b, err := hex.DecodeString(s)
@ -98,7 +98,7 @@ func NewPublicKeyFromASN1(data []byte) (*PublicKey, error) {
return &key, nil
}
// decodeCompressedY performs decompression of Y coordinate for given X and Y's least significant bit
// decodeCompressedY performs decompression of Y coordinate for given X and Y's least significant bit.
func decodeCompressedY(x *big.Int, ylsb uint) (*big.Int, error) {
c := elliptic.P256()
cp := c.Params()
@ -210,7 +210,7 @@ func (p *PublicKey) Address() string {
}
// Verify returns true if the signature is valid and corresponds
// to the hash and public key
// to the hash and public key.
func (p *PublicKey) Verify(signature []byte, hash []byte) bool {
publicKey := &ecdsa.PublicKey{}

View file

@ -47,7 +47,7 @@ func WIFEncode(key []byte, version byte, compressed bool) (s string, err error)
return
}
// WIFDecode decoded the given WIF string into a WIF struct.
// WIFDecode decodes the given WIF string into a WIF struct.
func WIFDecode(wif string, version byte) (*WIF, error) {
b, err := crypto.Base58CheckDecode(wif)
if err != nil {
@ -72,7 +72,7 @@ func WIFDecode(wif string, version byte) (*WIF, error) {
S: wif,
}
// This is an uncompressed WIF
// This is an uncompressed WIF.
if len(b) == 33 {
w.Compressed = false
return w, nil

View file

@ -37,7 +37,7 @@ func NewMerkleTree(hashes []util.Uint256) (*MerkleTree, error) {
}, nil
}
// Root return the computed root hash of the MerkleTree.
// Root returns the computed root hash of the MerkleTree.
func (t *MerkleTree) Root() util.Uint256 {
return t.root.hash
}

View file

@ -8,7 +8,7 @@ import "github.com/CityOfZion/neo-go/pkg/interop/transaction"
// Block stubs a NEO block type.
type Block struct{}
// GetTransactionCount return the number of recorded transactions in the given block.
// GetTransactionCount returns the number of recorded transactions in the given block.
func GetTransactionCount(b Block) int {
return 0
}

View file

@ -23,7 +23,7 @@ func Value(e Enumerator) interface{} {
return nil
}
// Concat concats the 2 given enumerators.
// Concat concatenates the 2 given enumerators.
func Concat(a, b Enumerator) Enumerator {
return Enumerator{}
}

View file

@ -5,19 +5,19 @@ import "github.com/CityOfZion/neo-go/pkg/interop/iterator"
// Package storage provides function signatures that can be used inside
// smart contracts that are written in the neo-go framework.
// Context represents the storage context
// Context represents the storage context.
type Context struct{}
// GetContext returns the storage context
// GetContext returns the storage context.
func GetContext() Context { return Context{} }
// Put value at given key
// Put value at given key.
func Put(ctx Context, key interface{}, value interface{}) {}
// Get value matching given key
// Get value matching given key.
func Get(ctx Context, key interface{}) interface{} { return 0 }
// Delete key value pair from storage
// Delete key value pair from storage.
func Delete(ctx Context, key interface{}) {}
// Find returns an iterator.Iterator over the keys that matched the given key.

View file

@ -6,8 +6,8 @@ import (
"io"
)
//BinReader is a convenient wrapper around a io.Reader and err object
// Used to simplify error handling when reading into a struct with many fields
// BinReader is a convenient wrapper around a io.Reader and err object.
// Used to simplify error handling when reading into a struct with many fields.
type BinReader struct {
r io.Reader
Err error
@ -25,7 +25,7 @@ func NewBinReaderFromBuf(b []byte) *BinReader {
}
// ReadLE reads from the underlying io.Reader
// into the interface v in little-endian format
// into the interface v in little-endian format.
func (r *BinReader) ReadLE(v interface{}) {
if r.Err != nil {
return
@ -34,7 +34,7 @@ func (r *BinReader) ReadLE(v interface{}) {
}
// ReadBE reads from the underlying io.Reader
// into the interface v in big-endian format
// into the interface v in big-endian format.
func (r *BinReader) ReadBE(v interface{}) {
if r.Err != nil {
return
@ -43,7 +43,7 @@ func (r *BinReader) ReadBE(v interface{}) {
}
// ReadVarUint reads a variable-length-encoded integer from the
// underlying reader
// underlying reader.
func (r *BinReader) ReadVarUint() uint64 {
if r.Err != nil {
return 0
@ -80,7 +80,7 @@ func (r *BinReader) ReadBytes() []byte {
return b
}
// ReadString calls ReadBytes and casts the results as a string
// ReadString calls ReadBytes and casts the results as a string.
func (r *BinReader) ReadString() string {
b := r.ReadBytes()
return string(b)

View file

@ -5,9 +5,9 @@ import (
"io"
)
//BinWriter is a convenient wrapper around a io.Writer and err object
// BinWriter is a convenient wrapper around a io.Writer and err object.
// Used to simplify error handling when writing into a io.Writer
// from a struct with many fields
// from a struct with many fields.
type BinWriter struct {
w io.Writer
Err error
@ -18,7 +18,7 @@ func NewBinWriterFromIO(iow io.Writer) *BinWriter {
return &BinWriter{w: iow}
}
// WriteLE writes into the underlying io.Writer from an object v in little-endian format
// WriteLE writes into the underlying io.Writer from an object v in little-endian format.
func (w *BinWriter) WriteLE(v interface{}) {
if w.Err != nil {
return
@ -26,7 +26,7 @@ func (w *BinWriter) WriteLE(v interface{}) {
w.Err = binary.Write(w.w, binary.LittleEndian, v)
}
// WriteBE writes into the underlying io.Writer from an object v in big-endian format
// WriteBE writes into the underlying io.Writer from an object v in big-endian format.
func (w *BinWriter) WriteBE(v interface{}) {
if w.Err != nil {
return
@ -34,7 +34,7 @@ func (w *BinWriter) WriteBE(v interface{}) {
w.Err = binary.Write(w.w, binary.BigEndian, v)
}
// WriteVarUint writes a uint64 into the underlying writer using variable-length encoding
// WriteVarUint writes a uint64 into the underlying writer using variable-length encoding.
func (w *BinWriter) WriteVarUint(val uint64) {
if w.Err != nil {
return
@ -61,13 +61,13 @@ func (w *BinWriter) WriteVarUint(val uint64) {
}
// WriteBytes writes a variable length byte array into the underlying io.Writer
// WriteBytes writes a variable length byte array into the underlying io.Writer.
func (w *BinWriter) WriteBytes(b []byte) {
w.WriteVarUint(uint64(len(b)))
w.WriteLE(b)
}
// WriteString writes a variable length string into the underlying io.Writer
// WriteString writes a variable length string into the underlying io.Writer.
func (w *BinWriter) WriteString(s string) {
w.WriteBytes([]byte(s))
}

View file

@ -24,14 +24,14 @@ type counterWriter struct {
counter int
}
// Write implements the io.Writer interface
// Write implements the io.Writer interface.
func (cw *counterWriter) Write(p []byte) (int, error) {
n := len(p)
cw.counter += n
return n, nil
}
// getVarIntSize returns the size in number of bytes of a variable integer
// getVarIntSize returns the size in number of bytes of a variable integer.
// (reference: GetVarSize(int value), https://github.com/neo-project/neo/blob/master/neo/IO/Helper.cs)
func getVarIntSize(value int) int {
var size uintptr

View file

@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
)
// Mock structure to test getting size of an array of serializable things
// Mock structure to test getting size of an array of serializable things.
type smthSerializable struct {
some [42]byte
}

View file

@ -85,7 +85,7 @@ func (d *DefaultDiscovery) pushToPoolOrDrop(addr string) {
}
}
// RequestRemote will try to establish a connection with n nodes.
// RequestRemote tries to establish a connection with n nodes.
func (d *DefaultDiscovery) RequestRemote(n int) {
d.requestCh <- n
}

View file

@ -32,11 +32,11 @@ type Message struct {
// the extra part is filled with 0.
Command [cmdSize]byte
// Length of the payload
// Length of the payload.
Length uint32
// Checksum is the first 4 bytes of the value that two times SHA256
// hash of the payload
// hash of the payload.
Checksum uint32
// Payload send with the message.
@ -146,7 +146,7 @@ func (m *Message) CommandType() CommandType {
}
}
// Decode a Message from the given reader.
// Decode decodes a Message from the given reader.
func (m *Message) Decode(br *io.BinReader) error {
br.ReadLE(&m.Magic)
br.ReadLE(&m.Command)
@ -210,7 +210,7 @@ func (m *Message) decodePayload(br *io.BinReader) error {
return nil
}
// Encode a Message to any given BinWriter.
// Encode encodes a Message to any given BinWriter.
func (m *Message) Encode(br *io.BinWriter) error {
br.WriteLE(m.Magic)
br.WriteLE(m.Command)

View file

@ -13,7 +13,7 @@ type GetBlocks struct {
HashStop util.Uint256
}
// NewGetBlocks return a pointer to a GetBlocks object.
// NewGetBlocks returns a pointer to a GetBlocks object.
func NewGetBlocks(start []util.Uint256, stop util.Uint256) *GetBlocks {
return &GetBlocks{
HashStart: start,

View file

@ -6,12 +6,12 @@ import (
log "github.com/sirupsen/logrus"
)
// Headers payload
// Headers payload.
type Headers struct {
Hdrs []*core.Header
}
// Users can at most request 2k header
// Users can at most request 2k header.
const (
maxHeadersAllowed = 2000
)

View file

@ -37,7 +37,7 @@ const (
ConsensusType InventoryType = 0xe0 // 224
)
// Inventory payload
// Inventory payload.
type Inventory struct {
// Type if the object hash.
Type InventoryType

View file

@ -7,10 +7,10 @@ import (
)
// Size of the payload not counting UserAgent encoding (which is at least 1 byte
// for zero-length string)
// for zero-length string).
const minVersionSize = 27
// List of Services offered by the node
// List of Services offered by the node.
const (
nodePeerService uint64 = 1
// BloomFilerService uint64 = 2 // Not implemented

View file

@ -1,6 +1,6 @@
package network
// RelayReason is the type which describes the different relay outcome
// RelayReason is the type which describes the different relay outcome.
type RelayReason uint8
// List of valid RelayReason.

View file

@ -16,7 +16,7 @@ import (
)
const (
// peer numbers are arbitrary at the moment
// peer numbers are arbitrary at the moment.
minPeers = 5
maxPeers = 20
maxBlockBatch = 200
@ -255,8 +255,8 @@ func (s *Server) handleVersionCmd(p Peer, version *payload.Version) error {
return p.SendVersionAck(NewMessage(s.Net, CMDVerack, nil))
}
// handleHeadersCmd will process the headers it received from its peer.
// if the headerHeight of the blockchain still smaller then the peer
// handleHeadersCmd processes the headers received from its peer.
// If the headerHeight of the blockchain still smaller then the peer
// the server will request more headers.
// This method could best be called in a separate routine.
func (s *Server) handleHeadersCmd(p Peer, headers *payload.Headers) {
@ -277,7 +277,7 @@ func (s *Server) handleBlockCmd(p Peer, block *core.Block) error {
return s.bQueue.putBlock(block)
}
// handleInvCmd will process the received inventory.
// handleInvCmd processes the received inventory.
func (s *Server) handleInvCmd(p Peer, inv *payload.Inventory) error {
if !inv.Type.Valid() || len(inv.Hashes) == 0 {
return errInvalidInvType
@ -310,7 +310,7 @@ func (s *Server) handleGetAddrCmd(p Peer) error {
return p.WriteMsg(NewMessage(s.Net, CMDAddr, alist))
}
// requestHeaders will send a getheaders message to the peer.
// requestHeaders sends a getheaders message to the peer.
// The peer will respond with headers op to a count of 2000.
func (s *Server) requestHeaders(p Peer) error {
start := []util.Uint256{s.chain.CurrentHeaderHash()}
@ -318,7 +318,7 @@ func (s *Server) requestHeaders(p Peer) error {
return p.WriteMsg(NewMessage(s.Net, CMDGetHeaders, payload))
}
// requestBlocks will send a getdata message to the peer
// requestBlocks sends a getdata message to the peer
// to sync up in blocks. A maximum of maxBlockBatch will
// send at once.
func (s *Server) requestBlocks(p Peer) error {
@ -341,7 +341,7 @@ func (s *Server) requestBlocks(p Peer) error {
return nil
}
// handleMessage will process the given message.
// handleMessage processes the given message.
func (s *Server) handleMessage(peer Peer, msg *Message) error {
// Make sure both server and peer are operating on
// the same network.
@ -414,7 +414,7 @@ func (s *Server) RelayTxn(t *transaction.Transaction) RelayReason {
return RelaySucceed
}
// RelayDirectly relay directly the inventory to the remote peers.
// RelayDirectly relays directly the inventory to the remote peers.
// Reference: the method OnRelayDirectly in C#: https://github.com/neo-project/neo/blob/master/neo/Network/P2P/LocalNode.cs#L166
func (s *Server) RelayDirectly(p Peer, inv *payload.Inventory) {
if !p.Version().Relay {

View file

@ -18,7 +18,7 @@ type TCPTransport struct {
var reClosedNetwork = regexp.MustCompile(".* use of closed network connection")
// NewTCPTransport return a new TCPTransport that will listen for
// NewTCPTransport returns a new TCPTransport that will listen for
// new incoming peer connections.
func NewTCPTransport(s *Server, bindAddr string) *TCPTransport {
return &TCPTransport{

View file

@ -52,7 +52,7 @@ type ClientOptions struct {
Version string
}
// NewClient return a new Client ready to use.
// NewClient returns a new Client ready to use.
func NewClient(ctx context.Context, endpoint string, opts ClientOptions) (*Client, error) {
url, err := url.Parse(endpoint)
if err != nil {

View file

@ -9,7 +9,7 @@ import "github.com/CityOfZion/neo-go/pkg/util"
*/
type (
// NeoScanServer stores NEOSCAN URL and API path
// NeoScanServer stores NEOSCAN URL and API path.
NeoScanServer struct {
URL string // "protocol://host:port/"
Path string // path to API endpoint without wallet address
@ -39,7 +39,7 @@ type (
}
)
// GlobalAssets stores a map of asset IDs to user-friendly strings ("NEO"/"GAS");
// GlobalAssets stores a map of asset IDs to user-friendly strings ("NEO"/"GAS").
var GlobalAssets = map[string]string{
"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b": "NEO",
"602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7": "GAS",

View file

@ -5,7 +5,7 @@ import (
)
type (
// Param represent a param either passed to
// Param represents a param either passed to
// the server or to send to a server using
// the client.
Param struct {

View file

@ -5,7 +5,7 @@ import (
)
type (
// Params represent the JSON-RPC params.
// Params represents the JSON-RPC params.
Params []Param
)

View file

@ -27,7 +27,7 @@ import (
// return resp, nil
// }
// GetAccountState will return detailed information about a NEO account.
// GetAccountState returns detailed information about a NEO account.
func (c *Client) GetAccountState(address string) (*AccountStateResponse, error) {
var (
params = newParams(address)
@ -52,7 +52,7 @@ func (c *Client) InvokeScript(script string) (*InvokeScriptResponse, error) {
return resp, nil
}
// InvokeFunction return the results after calling a the smart contract scripthash
// InvokeFunction returns the results after calling the smart contract scripthash
// with the given operation and parameters.
// NOTE: this is test invoke and will not affect the blockchain.
func (c *Client) InvokeFunction(script, operation string, params []smartcontract.Parameter) (*InvokeScriptResponse, error) {
@ -66,7 +66,7 @@ func (c *Client) InvokeFunction(script, operation string, params []smartcontract
return resp, nil
}
// Invoke returns the results after calling a the smart contract scripthash
// Invoke returns the results after calling the smart contract scripthash
// with the given parameters.
func (c *Client) Invoke(script string, params []smartcontract.Parameter) (*InvokeScriptResponse, error) {
var (

View file

@ -56,7 +56,7 @@ func (s *Server) Start(errChan chan error) {
errChan <- s.ListenAndServe()
}
// Shutdown override the http.Server Shutdown
// Shutdown overrides the http.Server Shutdown
// method.
func (s *Server) Shutdown() error {
log.WithFields(log.Fields{

View file

@ -13,7 +13,7 @@ import (
// StackParamType represents different types of stack values.
type StackParamType int
// All possible StackParamType values are listed here
// All possible StackParamType values are listed here.
const (
Unknown StackParamType = -1
Signature StackParamType = 0x00
@ -114,7 +114,7 @@ type rawStackParam struct {
Value json.RawMessage `json:"value"`
}
// UnmarshalJSON implements Unmarshaler interface
// UnmarshalJSON implements Unmarshaler interface.
func (p *StackParam) UnmarshalJSON(data []byte) (err error) {
var (
r rawStackParam
@ -179,7 +179,7 @@ func (p *StackParam) UnmarshalJSON(data []byte) (err error) {
return
}
// StackParams in an array of StackParam (TODO: drop it?).
// StackParams is an array of StackParam (TODO: drop it?).
type StackParams []StackParam
// TryParseArray converts an array of StackParam into an array of more appropriate things.

View file

@ -81,7 +81,7 @@ type SendToAddressResponse struct {
Result *TxResponse
}
// GetRawTxResponse struct represents verbose output of `getrawtransaction` RPC call.
// GetRawTxResponse represents verbose output of `getrawtransaction` RPC call.
type GetRawTxResponse struct {
responseHeader
Error *Error `json:"error"`

View file

@ -19,14 +19,14 @@ type AccountState struct {
Balances []Balance `json:"balances"`
}
// Balances type for sorting balances in rpc response
// Balances type for sorting balances in rpc response.
type Balances []Balance
func (b Balances) Len() int { return len(b) }
func (b Balances) Less(i, j int) bool { return bytes.Compare(b[i].Asset[:], b[j].Asset[:]) != -1 }
func (b Balances) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
// Balance response wrapper
// Balance response wrapper.
type Balance struct {
Asset util.Uint256 `json:"asset"`
Value util.Fixed8 `json:"value"`

View file

@ -24,7 +24,7 @@ func CreateSignatureRedeemScript(key *keys.PublicKey) ([]byte, error) {
return buf.Bytes(), nil
}
// CreateMultiSigRedeemScript will create a script runnable by the VM.
// CreateMultiSigRedeemScript creates a script runnable by the VM.
func CreateMultiSigRedeemScript(m int, publicKeys keys.PublicKeys) ([]byte, error) {
if m <= 1 {
return nil, fmt.Errorf("param m cannot be smaller or equal to 1 got %d", m)

View file

@ -2,7 +2,7 @@ package smartcontract
import "github.com/CityOfZion/neo-go/pkg/util"
// ParamType represent the Type of the contract parameter
// ParamType represents the Type of the contract parameter.
type ParamType byte
// A list of supported smart contract parameter types.
@ -31,7 +31,7 @@ const (
// Parameter represents a smart contract parameter.
type Parameter struct {
// Type of the parameter
// Type of the parameter.
Type ParamType `json:"type"`
// The actual value of the parameter.
Value interface{} `json:"value"`

View file

@ -1,6 +1,6 @@
package util
// ArrayReverse return a reversed version of the given byte slice.
// ArrayReverse returns a reversed version of the given byte slice.
func ArrayReverse(b []byte) []byte {
// Protect from big.Ints that have 1 len bytes.
if len(b) < 2 {

View file

@ -39,7 +39,7 @@ func (u Uint160) Bytes() []byte {
return u[:]
}
// BytesReverse return a reversed byte representation of u.
// BytesReverse returns a reversed byte representation of u.
func (u Uint160) BytesReverse() []byte {
return ArrayReverse(u.Bytes())
}
@ -49,7 +49,7 @@ func (u Uint160) String() string {
return hex.EncodeToString(u.Bytes())
}
// ReverseString is the same as String, but returnes an inversed representation.
// ReverseString is the same as String, but returns a reversed representation.
func (u Uint160) ReverseString() string {
return hex.EncodeToString(u.BytesReverse())
}

View file

@ -14,7 +14,7 @@ func TestUint160UnmarshalJSON(t *testing.T) {
t.Fatal(err)
}
// UnmarshalJSON should decode hex-strings
// UnmarshalJSON decodes hex-strings
var u1, u2 Uint160
if err = u1.UnmarshalJSON([]byte(`"` + str + `"`)); err != nil {
@ -27,7 +27,7 @@ func TestUint160UnmarshalJSON(t *testing.T) {
t.Fatal(err)
}
// UnmarshalJSON should decode hex-strings prefixed by 0x
// UnmarshalJSON decodes hex-strings prefixed by 0x
if err = u2.UnmarshalJSON(s); err != nil {
t.Fatal(err)
}

View file

@ -14,7 +14,7 @@ func TestUint256UnmarshalJSON(t *testing.T) {
t.Fatal(err)
}
// UnmarshalJSON should decode hex-strings
// UnmarshalJSON decodes hex-strings
var u1, u2 Uint256
if err = u1.UnmarshalJSON([]byte(`"` + str + `"`)); err != nil {
@ -27,7 +27,7 @@ func TestUint256UnmarshalJSON(t *testing.T) {
t.Fatal(err)
}
// UnmarshalJSON should decode hex-strings prefixed by 0x
// UnmarshalJSON decodes hex-strings prefixed by 0x
if err = u2.UnmarshalJSON(s); err != nil {
t.Fatal(err)
}

View file

@ -107,7 +107,7 @@ func resolveEntryPoint(entry string, pkg *loader.PackageInfo) (*ast.FuncDecl, *a
return main, file
}
// indexOfStruct will return the index of the given field inside that struct.
// indexOfStruct returns the index of the given field inside that struct.
// 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++ {
@ -125,7 +125,7 @@ func (f funcUsage) funcUsed(name string) bool {
return ok
}
// hasReturnStmt look if the given FuncDecl has a return statement.
// hasReturnStmt looks if the given FuncDecl has a return statement.
func hasReturnStmt(decl ast.Node) (b bool) {
ast.Inspect(decl, func(node ast.Node) bool {
if _, ok := node.(*ast.ReturnStmt); ok {

View file

@ -23,10 +23,10 @@ type codegen struct {
// Information about the program with all its dependencies.
buildInfo *buildInfo
// prog holds the output buffer
// prog holds the output buffer.
prog *bytes.Buffer
// Type information
// Type information.
typeInfo *types.Info
// A mapping of func identifiers with their scope.
@ -50,7 +50,7 @@ func (c *codegen) setLabel(l int) {
c.l[l] = c.pc() + 1
}
// pc return the program offset off the last instruction.
// pc returns the program offset off the last instruction.
func (c *codegen) pc() int {
return c.prog.Len() - 1
}
@ -73,10 +73,10 @@ func (c *codegen) emitLoadConst(t types.TypeAndValue) {
b := byte(val)
emitBytes(c.prog, []byte{b})
default:
log.Fatalf("compiler don't know how to convert this basic type: %v", t)
log.Fatalf("compiler doesn't know how to convert this basic type: %v", t)
}
default:
log.Fatalf("compiler don't know how to convert this constant: %v", t)
log.Fatalf("compiler doesn't know how to convert this constant: %v", t)
}
}
@ -118,7 +118,7 @@ func (c *codegen) emitStoreStructField(i int) {
emitOpcode(c.prog, vm.SETITEM)
}
// convertGlobals will traverse the AST and only convert global declarations.
// convertGlobals traverses the AST and only converts global declarations.
// If we call this in convertFuncDecl then it will load all global variables
// into the scope of the function.
func (c *codegen) convertGlobals(f ast.Node) {
@ -331,7 +331,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
typ = c.typeInfo.ObjectOf(t.Sel).Type().Underlying()
default:
ln := len(n.Elts)
// ByteArrays need a different approach then normal arrays.
// ByteArrays needs a different approach than normal arrays.
if isByteArray(n, c.typeInfo) {
c.convertByteArray(n)
return nil
@ -760,7 +760,7 @@ func (c *codegen) newFunc(decl *ast.FuncDecl) *funcScope {
return f
}
// CodeGen is the function that compiles the program to bytecode.
// CodeGen compiles the program to bytecode.
func CodeGen(info *buildInfo) (*bytes.Buffer, error) {
pkg := info.program.Package(info.initialPackage)
c := &codegen{
@ -771,32 +771,32 @@ func CodeGen(info *buildInfo) (*bytes.Buffer, error) {
typeInfo: &pkg.Info,
}
// Resolve the entrypoint of the program
// Resolve the entrypoint of the program.
main, mainFile := resolveEntryPoint(mainIdent, pkg)
if main == nil {
log.Fatal("could not find func main. did you forgot to declare it?")
log.Fatal("could not find func main. Did you forget to declare it?")
}
funUsage := analyzeFuncUsage(info.program.AllPackages)
// Bring all imported functions into scope
// Bring all imported functions into scope.
for _, pkg := range info.program.AllPackages {
for _, f := range pkg.Files {
c.resolveFuncDecls(f)
}
}
// convert the entry point first
// convert the entry point first.
c.convertFuncDecl(mainFile, main)
// sort map keys to generate code deterministically
// sort map keys to generate code deterministically.
keys := make([]*types.Package, 0, len(info.program.AllPackages))
for p := range info.program.AllPackages {
keys = append(keys, p)
}
sort.Slice(keys, func(i, j int) bool { return keys[i].Path() < keys[j].Path() })
// Generate the code for the program
// Generate the code for the program.
for _, k := range keys {
pkg := info.program.AllPackages[k]
c.typeInfo = &pkg.Info
@ -805,7 +805,7 @@ func CodeGen(info *buildInfo) (*bytes.Buffer, error) {
for _, decl := range f.Decls {
switch n := decl.(type) {
case *ast.FuncDecl:
// Dont convert the function if its not used. This will save a lot
// Don't convert the function if it's not used. This will save a lot
// of bytecode space.
if n.Name.Name != mainIdent && funUsage.funcUsed(n.Name.Name) {
c.convertFuncDecl(f, n)

View file

@ -28,7 +28,7 @@ type Options struct {
// The name of the output file.
Outfile string
// Debug will output an hex encoded string of the generated bytecode.
// Debug outputs a hex encoded string of the generated bytecode.
Debug bool
}

View file

@ -7,7 +7,7 @@ import (
// A funcScope represents the scope within the function context.
// It holds al the local variables along with the initialized struct positions.
type funcScope struct {
// identifier of the function.
// Identifier of the function.
name string
// Selector of the function if there is any. Only functions imported
@ -31,7 +31,7 @@ type funcScope struct {
// return value to the stack size.
voidCalls map[*ast.CallExpr]bool
// local variable counter
// Local variable counter.
i int
}
@ -46,7 +46,7 @@ func newFuncScope(decl *ast.FuncDecl, label int) *funcScope {
}
}
// analyzeVoidCalls will check for functions that are not assigned
// analyzeVoidCalls checks for functions that are not assigned
// and therefore we need to cleanup the return value from the stack.
func (c *funcScope) analyzeVoidCalls(node ast.Node) bool {
switch n := node.(type) {

View file

@ -6,7 +6,7 @@ import (
"github.com/CityOfZion/neo-go/pkg/io"
)
// Context represent the current execution context of the VM.
// Context represents the current execution context of the VM.
type Context struct {
// Instruction pointer.
ip int
@ -17,11 +17,11 @@ type Context struct {
// The raw program script.
prog []byte
// Breakpoints
// Breakpoints.
breakPoints []int
}
// NewContext return a new Context object.
// NewContext returns a new Context object.
func NewContext(b []byte) *Context {
return &Context{
prog: b,

View file

@ -7,14 +7,14 @@ import (
// InteropFunc allows to hook into the VM.
type InteropFunc func(vm *VM) error
// runtimeLog will handle the syscall "Neo.Runtime.Log" for printing and logging stuff.
// runtimeLog handles the syscall "Neo.Runtime.Log" for printing and logging stuff.
func runtimeLog(vm *VM) error {
item := vm.Estack().Pop()
fmt.Printf("NEO-GO-VM (log) > %s\n", item.Value())
return nil
}
// runtimeNotify will handle the syscall "Neo.Runtime.Notify" for printing and logging stuff.
// runtimeNotify handles the syscall "Neo.Runtime.Notify" for printing and logging stuff.
func runtimeNotify(vm *VM) error {
item := vm.Estack().Pop()
fmt.Printf("NEO-GO-VM (notify) > %s\n", item.Value())

View file

@ -164,19 +164,19 @@ func NewStack(n string) *Stack {
return s
}
// Clear will clear all elements on the stack and set its length to 0.
// Clear clears all elements on the stack and set its length to 0.
func (s *Stack) Clear() {
s.top.next = &s.top
s.top.prev = &s.top
s.len = 0
}
// Len return the number of elements that are on the stack.
// Len returns the number of elements that are on the stack.
func (s *Stack) Len() int {
return s.len
}
// insert will insert the element after element (at) on the stack.
// insert inserts the element after element (at) on the stack.
func (s *Stack) insert(e, at *Element) *Element {
// If we insert an element that is already popped from this stack,
// we need to clean it up, there are still pointers referencing to it.
@ -194,7 +194,7 @@ func (s *Stack) insert(e, at *Element) *Element {
return e
}
// InsertAt will insert the given item (n) deep on the stack.
// InsertAt inserts the given item (n) deep on the stack.
// Be very careful using it and _always_ check both e and n before invocation
// as it will silently do wrong things otherwise.
func (s *Stack) InsertAt(e *Element, n int) *Element {
@ -210,7 +210,7 @@ func (s *Stack) Push(e *Element) {
s.insert(e, &s.top)
}
// PushVal will push the given value on the stack. It will infer the
// PushVal pushes the given value on the stack. It will infer the
// underlying StackItem to its corresponding type.
func (s *Stack) PushVal(v interface{}) {
s.Push(NewElement(v))
@ -273,7 +273,7 @@ func (s *Stack) Remove(e *Element) *Element {
return e
}
// Dup will duplicate and return the element at position n.
// 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.
// s.Push(s.Dup(0)) // is the correct approach.
@ -288,7 +288,7 @@ func (s *Stack) Dup(n int) *Element {
}
}
// Iter will iterate over all the elements int the stack, starting from the top
// Iter iterates over all the elements int the stack, starting from the top
// of the stack.
// s.Iter(func(elem *Element) {
// // do something with the element.

View file

@ -17,7 +17,7 @@ const (
breakState
)
// HasFlag check for State flag presence.
// HasFlag checks for State flag presence.
func (s State) HasFlag(f State) bool {
return s&f != 0
}
@ -63,12 +63,12 @@ func StateFromString(s string) (st State, err error) {
return
}
// MarshalJSON implements the json.Marshaler interface
// MarshalJSON implements the json.Marshaler interface.
func (s State) MarshalJSON() (data []byte, err error) {
return []byte(`"` + s.String() + `"`), nil
}
// UnmarshalJSON implements the json.Marshaler interface
// UnmarshalJSON implements the json.Marshaler interface.
func (s *State) UnmarshalJSON(data []byte) (err error) {
l := len(data)
if l < 2 || data[0] != '"' || data[l-1] != '"' {

View file

@ -26,7 +26,7 @@ type Account struct {
// Label is a label the user had made for this account.
Label string `json:"label"`
// contract is a Contract object which describes the details of the contract.
// Contract is a Contract object which describes the details of the contract.
// This field can be null (for watch-only address).
Contract *Contract `json:"contract"`
@ -60,7 +60,7 @@ func NewAccount() (*Account, error) {
return newAccountFromPrivateKey(priv), nil
}
// DecryptAccount decrypt the encryptedWIF with the given passphrase and
// DecryptAccount decrypts the encryptedWIF with the given passphrase and
// return the decrypted Account.
func DecryptAccount(encryptedWIF, passphrase string) (*Account, error) {
wif, err := keys.NEP2Decrypt(encryptedWIF, passphrase)
@ -90,7 +90,7 @@ func NewAccountFromWIF(wif string) (*Account, error) {
return newAccountFromPrivateKey(privKey), nil
}
// newAccountFromPrivateKey created a wallet from the given PrivateKey.
// newAccountFromPrivateKey creates a wallet from the given PrivateKey.
func newAccountFromPrivateKey(p *keys.PrivateKey) *Account {
pubKey := p.PublicKey()
pubAddr := p.Address()