Skip to content

Commit

Permalink
Use exp/slices and exp/maps to simplify some code
Browse files Browse the repository at this point in the history
The intent is to only make changes where the result is clearer, and to
catch enough cases that the next time someone does something similar,
they will have seen the new, clearer way to write the thing they intend.
  • Loading branch information
jannotti committed Jun 18, 2023
1 parent 4d6e50d commit 2229778
Show file tree
Hide file tree
Showing 33 changed files with 114 additions and 191 deletions.
5 changes: 2 additions & 3 deletions agreement/autopsy.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
"golang.org/x/exp/slices"
)

// An Autopsy is a trace of the ordered input events and output
Expand Down Expand Up @@ -102,9 +103,7 @@ func (m *multiCloser) Close() error {

// makeMultiCloser returns a Closer that closes all the given closers.
func makeMultiCloser(closers ...io.Closer) io.Closer {
r := make([]io.Closer, len(closers))
copy(r, closers)
return &multiCloser{r}
return &multiCloser{slices.Clone(closers)}
}

type autopsyTrace struct {
Expand Down
6 changes: 2 additions & 4 deletions cmd/algokey/keyreg.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"strings"

"github.com/spf13/cobra"
"golang.org/x/exp/maps"

"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/account"
Expand Down Expand Up @@ -94,10 +95,7 @@ func init() {
"betanet": mustConvertB64ToDigest("mFgazF+2uRS1tMiL9dsj01hJGySEmPN28B/TjjvpVW0="),
"devnet": mustConvertB64ToDigest("sC3P7e2SdbqKJK0tbiCdK9tdSpbe6XeCGKdoNzmlj0E="),
}
validNetworkList = make([]string, 0, len(validNetworks))
for k := range validNetworks {
validNetworkList = append(validNetworkList, k)
}
validNetworkList = maps.Keys(validNetworks)
}

func mustConvertB64ToDigest(b64 string) (digest crypto.Digest) {
Expand Down
13 changes: 5 additions & 8 deletions cmd/goal/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"time"

"github.com/spf13/cobra"
"golang.org/x/exp/slices"

"github.com/algorand/go-algorand/cmd/util/datadir"
"github.com/algorand/go-algorand/config"
Expand Down Expand Up @@ -557,35 +558,31 @@ var infoCmd = &cobra.Command{
func printAccountInfo(client libgoal.Client, address string, onlyShowAssetIds bool, account model.Account) bool {
var createdAssets []model.Asset
if account.CreatedAssets != nil {
createdAssets = make([]model.Asset, len(*account.CreatedAssets))
copy(createdAssets, *account.CreatedAssets)
createdAssets = slices.Clone(*account.CreatedAssets)
sort.Slice(createdAssets, func(i, j int) bool {
return createdAssets[i].Index < createdAssets[j].Index
})
}

var heldAssets []model.AssetHolding
if account.Assets != nil {
heldAssets = make([]model.AssetHolding, len(*account.Assets))
copy(heldAssets, *account.Assets)
heldAssets = slices.Clone(*account.Assets)
sort.Slice(heldAssets, func(i, j int) bool {
return heldAssets[i].AssetID < heldAssets[j].AssetID
})
}

var createdApps []model.Application
if account.CreatedApps != nil {
createdApps = make([]model.Application, len(*account.CreatedApps))
copy(createdApps, *account.CreatedApps)
createdApps = slices.Clone(*account.CreatedApps)
sort.Slice(createdApps, func(i, j int) bool {
return createdApps[i].Id < createdApps[j].Id
})
}

var optedInApps []model.ApplicationLocalState
if account.AppsLocalState != nil {
optedInApps = make([]model.ApplicationLocalState, len(*account.AppsLocalState))
copy(optedInApps, *account.AppsLocalState)
optedInApps = slices.Clone(*account.AppsLocalState)
sort.Slice(optedInApps, func(i, j int) bool {
return optedInApps[i].Id < optedInApps[j].Id
})
Expand Down
4 changes: 2 additions & 2 deletions cmd/tealdbg/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/algorand/go-algorand/data/transactions/logic"
"github.com/algorand/go-algorand/ledger/apply"
"github.com/algorand/go-algorand/protocol"
"golang.org/x/exp/slices"
)

func protoFromString(protoString string) (name string, proto config.ConsensusParams, err error) {
Expand Down Expand Up @@ -190,8 +191,7 @@ func (a *AppState) clone() (b AppState) {
b.locals[addr][aid] = tkv.Clone()
}
}
b.logs = make([]string, len(a.logs))
copy(b.logs, a.logs)
b.logs = slices.Clone(a.logs)
b.innerTxns = cloneInners(a.innerTxns)
return
}
Expand Down
3 changes: 2 additions & 1 deletion crypto/merklearray/merkle.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"sort"

"github.com/algorand/go-algorand/crypto"
"golang.org/x/exp/slices"
)

const (
Expand Down Expand Up @@ -223,7 +224,7 @@ func (tree *Tree) Prove(idxs []uint64) (*Proof, error) {
idxs = VcIdxs
}

sort.Slice(idxs, func(i, j int) bool { return idxs[i] < idxs[j] })
slices.Sort(idxs)

return tree.createProof(idxs)
}
Expand Down
11 changes: 5 additions & 6 deletions crypto/merkletrie/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"encoding/binary"
"errors"
"fmt"
"sort"

"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
)

// storedNodeIdentifier is the "equivalent" of a node-ptr, but oriented around persisting the
Expand Down Expand Up @@ -446,11 +448,8 @@ func (mtc *merkleTrieCache) reallocatePendingPages(stats *CommitStats) (pagesToC
}

// create a sorted list of created pages
sortedCreatedPages := make([]uint64, 0, len(createdPages))
for page := range createdPages {
sortedCreatedPages = append(sortedCreatedPages, page)
}
sort.SliceStable(sortedCreatedPages, func(i, j int) bool { return sortedCreatedPages[i] < sortedCreatedPages[j] })
sortedCreatedPages := maps.Keys(createdPages)
slices.Sort(sortedCreatedPages)

mtc.reallocatedPages = make(map[uint64]map[storedNodeIdentifier]*node)

Expand Down
6 changes: 3 additions & 3 deletions crypto/merkletrie/committer.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package merkletrie

import "golang.org/x/exp/slices"

// Committer is the interface supporting serializing tries into persistent storage.
type Committer interface {
StorePage(page uint64, content []byte) error
Expand All @@ -40,9 +42,7 @@ func (mc *InMemoryCommitter) StorePage(page uint64, content []byte) error {
if content == nil {
delete(mc.memStore, page)
} else {
storedContent := make([]byte, len(content))
copy(storedContent, content)
mc.memStore[page] = storedContent
mc.memStore[page] = slices.Clone(content)
}
return nil
}
Expand Down
5 changes: 2 additions & 3 deletions crypto/merkletrie/committer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"testing"

"github.com/stretchr/testify/require"
"golang.org/x/exp/slices"

"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/test/partitiontest"
Expand All @@ -33,9 +34,7 @@ func (mc *InMemoryCommitter) Duplicate(flat bool) (out *InMemoryCommitter) {
if flat {
out.memStore[k] = v
} else {
bytes := make([]byte, len(v))
copy(bytes[:], v[:])
out.memStore[k] = bytes
out.memStore[k] = slices.Clone(v)
}
}
return
Expand Down
4 changes: 2 additions & 2 deletions crypto/merkletrie/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"unsafe"

"github.com/algorand/go-algorand/crypto"
"golang.org/x/exp/slices"
)

type childEntry struct {
Expand Down Expand Up @@ -339,8 +340,7 @@ func deserializeNode(buf []byte) (n *node, s int) {
if hashLength2 <= 0 {
return nil, hashLength2
}
n.hash = make([]byte, hashLength)
copy(n.hash, buf[hashLength2:hashLength2+int(hashLength)])
n.hash = slices.Clone(buf[hashLength2 : hashLength2+int(hashLength)])
s = hashLength2 + int(hashLength)
isLeaf := (buf[s] == 0)
s++
Expand Down
4 changes: 2 additions & 2 deletions daemon/algod/api/server/v2/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/daemon/algod/api/server/v2/generated/model"
"github.com/algorand/go-algorand/data/basics"
"golang.org/x/exp/slices"
)

// AssetHolding converts between basics.AssetHolding and model.AssetHolding
Expand Down Expand Up @@ -477,8 +478,7 @@ func AssetParamsToAsset(creator string, idx basics.AssetIndex, params *basics.As
Reserve: addrOrNil(params.Reserve),
}
if params.MetadataHash != ([32]byte{}) {
metadataHash := make([]byte, len(params.MetadataHash))
copy(metadataHash, params.MetadataHash[:])
metadataHash := slices.Clone(params.MetadataHash[:])
assetParams.MetadataHash = &metadataHash
}

Expand Down
4 changes: 2 additions & 2 deletions daemon/algod/api/server/v2/test/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (

"github.com/algorand/go-algorand/ledger/eval"
"github.com/algorand/go-algorand/ledger/ledgercore"
"golang.org/x/exp/slices"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -1028,8 +1029,7 @@ int 1`,

var expectedFailedAt *[]uint64
if len(scenario.FailedAt) != 0 {
clone := make([]uint64, len(scenario.FailedAt))
copy(clone, scenario.FailedAt)
clone := slices.Clone(scenario.FailedAt)
clone[0]++
expectedFailedAt = &clone
}
Expand Down
4 changes: 2 additions & 2 deletions daemon/algod/api/server/v2/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"github.com/algorand/go-codec/codec"
"github.com/labstack/echo/v4"
"golang.org/x/exp/slices"

"github.com/algorand/go-algorand/daemon/algod/api/server/v2/generated/model"
"github.com/algorand/go-algorand/data/basics"
Expand Down Expand Up @@ -431,8 +432,7 @@ func convertTxnGroupResult(txnGroupResult simulation.TxnGroupResult) PreEncodedS
}

if len(txnGroupResult.FailedAt) > 0 {
failedAt := make([]uint64, len(txnGroupResult.FailedAt))
copy(failedAt, txnGroupResult.FailedAt)
failedAt := slices.Clone[[]uint64, uint64](txnGroupResult.FailedAt)
encoded.FailedAt = &failedAt
}

Expand Down
10 changes: 2 additions & 8 deletions data/basics/teal.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"

"github.com/algorand/go-algorand/config"
"golang.org/x/exp/maps"
)

// DeltaAction is an enum of actions that may be performed when applying a
Expand Down Expand Up @@ -234,14 +235,7 @@ type TealKeyValue map[string]TealValue
// Clone returns a copy of a TealKeyValue that may be modified without
// affecting the original
func (tk TealKeyValue) Clone() TealKeyValue {
if tk == nil {
return nil
}
res := make(TealKeyValue, len(tk))
for k, v := range tk {
res[k] = v
}
return res
return maps.Clone(tk)
}

// ToStateSchema calculates the number of each value type in a TealKeyValue and
Expand Down
7 changes: 3 additions & 4 deletions data/basics/userBalance.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"github.com/algorand/go-algorand/crypto/merklesignature"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
"golang.org/x/exp/slices"
)

// Status is the delegation status of an account's MicroAlgos
Expand Down Expand Up @@ -268,10 +269,8 @@ type StateSchemas struct {
// affecting the original
func (ap *AppParams) Clone() (res AppParams) {
res = *ap
res.ApprovalProgram = make([]byte, len(ap.ApprovalProgram))
copy(res.ApprovalProgram, ap.ApprovalProgram)
res.ClearStateProgram = make([]byte, len(ap.ClearStateProgram))
copy(res.ClearStateProgram, ap.ClearStateProgram)
res.ApprovalProgram = slices.Clone(ap.ApprovalProgram)
res.ClearStateProgram = slices.Clone(ap.ClearStateProgram)
res.GlobalState = ap.GlobalState.Clone()
return
}
Expand Down
14 changes: 5 additions & 9 deletions data/transactions/logic/eval.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import (
"strings"

"golang.org/x/crypto/sha3"
"golang.org/x/exp/slices"

"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
Expand Down Expand Up @@ -5291,8 +5292,7 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs *txnFieldSpec, txn *t
if len(sv.Bytes) > cx.Proto.MaxTxnNoteBytes {
return fmt.Errorf("%s may not exceed %d bytes", fs.field, cx.Proto.MaxTxnNoteBytes)
}
txn.Note = make([]byte, len(sv.Bytes))
copy(txn.Note, sv.Bytes)
txn.Note = slices.Clone(sv.Bytes)
// GenesisID, GenesisHash unsettable: surely makes no sense
// Group unsettable: Can't make groups from AVM (yet?)
// Lease unsettable: This seems potentially useful.
Expand Down Expand Up @@ -5406,9 +5406,7 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs *txnFieldSpec, txn *t
if len(txn.ApplicationArgs) >= cx.Proto.MaxAppArgs {
return errors.New("too many application args")
}
new := make([]byte, len(sv.Bytes))
copy(new, sv.Bytes)
txn.ApplicationArgs = append(txn.ApplicationArgs, new)
txn.ApplicationArgs = append(txn.ApplicationArgs, slices.Clone(sv.Bytes))
case Accounts:
var new basics.Address
new, err = cx.assignAccount(sv)
Expand All @@ -5424,15 +5422,13 @@ func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs *txnFieldSpec, txn *t
if len(sv.Bytes) > maxPossible {
return fmt.Errorf("%s may not exceed %d bytes", fs.field, maxPossible)
}
txn.ApprovalProgram = make([]byte, len(sv.Bytes))
copy(txn.ApprovalProgram, sv.Bytes)
txn.ApprovalProgram = slices.Clone(sv.Bytes)
case ClearStateProgram:
maxPossible := cx.Proto.MaxAppProgramLen * (1 + cx.Proto.MaxExtraAppProgramPages)
if len(sv.Bytes) > maxPossible {
return fmt.Errorf("%s may not exceed %d bytes", fs.field, maxPossible)
}
txn.ClearStateProgram = make([]byte, len(sv.Bytes))
copy(txn.ClearStateProgram, sv.Bytes)
txn.ClearStateProgram = slices.Clone(sv.Bytes)
case ApprovalProgramPages:
maxPossible := cx.Proto.MaxAppProgramLen * (1 + cx.Proto.MaxExtraAppProgramPages)
txn.ApprovalProgram = append(txn.ApprovalProgram, sv.Bytes...)
Expand Down
13 changes: 5 additions & 8 deletions data/transactions/logic/evalCrypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import (

"github.com/consensys/gnark-crypto/ecc/bn254"
"github.com/stretchr/testify/require"
"golang.org/x/exp/slices"

"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/crypto/secp256k1"
Expand Down Expand Up @@ -331,8 +332,7 @@ load 0
byte 0x%s
==
&&`
pkTampered1 := make([]byte, len(pk))
copy(pkTampered1, pk)
pkTampered1 := slices.Clone(pk)
pkTampered1[0] = 0 // first byte is a prefix of either 0x02 or 0x03
pkTampered2 := make([]byte, len(pk)-1) // must be 33 bytes length
copy(pkTampered2, pk)
Expand Down Expand Up @@ -378,8 +378,7 @@ ecdsa_verify Secp256k1
s := sign[32:64]
v := int(sign[64])

rTampered := make([]byte, len(r))
copy(rTampered, r)
rTampered := slices.Clone(r)
rTampered[0] += byte(1) // intentional overflow

var verifyTests = []struct {
Expand Down Expand Up @@ -487,8 +486,7 @@ load 0
byte 0x%s
==
&&`
pkTampered1 := make([]byte, len(pk))
copy(pkTampered1, pk)
pkTampered1 := slices.Clone(pk)
pkTampered1[0] = 0 // first byte is a prefix of either 0x02 or 0x03
pkTampered2 := make([]byte, len(pk)-1) // must be 33 bytes length
copy(pkTampered2, pk)
Expand Down Expand Up @@ -533,8 +531,7 @@ ecdsa_verify Secp256r1
r := ri.Bytes()
s := si.Bytes()

rTampered := make([]byte, len(r))
copy(rTampered, r)
rTampered := slices.Clone(r)
rTampered[0] += byte(1) // intentional overflow

var verifyTests = []struct {
Expand Down
Loading

0 comments on commit 2229778

Please sign in to comment.