summaryrefslogtreecommitdiff
path: root/data/basics/userBalance_test.go
blob: 1670fe58d652fdecefd492f9811897c7afb0a47e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package basics

import (
	"fmt"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
)

func TestEmptyEncoding(t *testing.T) {
	partitiontest.PartitionTest(t)

	var ub BalanceRecord
	require.Equal(t, 1, len(protocol.Encode(&ub)))
}

func TestRewards(t *testing.T) {
	partitiontest.PartitionTest(t)

	proto := config.Consensus[protocol.ConsensusCurrentVersion]
	accountAlgos := []MicroAlgos{{Raw: 0}, {Raw: 8000}, {Raw: 13000}, {Raw: 83000}}
	for _, accountAlgo := range accountAlgos {
		ad := AccountData{
			Status:             Online,
			MicroAlgos:         accountAlgo,
			RewardsBase:        100,
			RewardedMicroAlgos: MicroAlgos{Raw: 25},
		}

		levels := []uint64{uint64(0), uint64(1), uint64(30), uint64(3000)}
		for _, level := range levels {
			money, rewards := ad.Money(proto, ad.RewardsBase+level)
			require.Equal(t, money.Raw, ad.MicroAlgos.Raw+level*ad.MicroAlgos.RewardUnits(proto))
			require.Equal(t, rewards.Raw, ad.RewardedMicroAlgos.Raw+level*ad.MicroAlgos.RewardUnits(proto))
		}
	}
}

func TestWithUpdatedRewardsPanics(t *testing.T) {
	partitiontest.PartitionTest(t)

	proto := config.Consensus[protocol.ConsensusCurrentVersion]
	t.Run("AlgoPanic", func(t *testing.T) {
		paniced := false
		func() {
			defer func() {
				if err := recover(); err != nil {
					if strings.Contains(fmt.Sprintf("%v", err), "overflowed account balance when applying rewards") {
						paniced = true
					} else {
						panic(err)
					}
				}
			}()
			a := AccountData{
				Status:             Online,
				MicroAlgos:         MicroAlgos{Raw: ^uint64(0)},
				RewardedMicroAlgos: MicroAlgos{Raw: 0},
				RewardsBase:        0,
			}
			a.WithUpdatedRewards(proto, 100)
		}()
		require.Equal(t, true, paniced)
	})

	t.Run("RewardsOverflow", func(t *testing.T) {
		a := AccountData{
			Status:             Online,
			MicroAlgos:         MicroAlgos{Raw: 80000000},
			RewardedMicroAlgos: MicroAlgos{Raw: ^uint64(0)},
			RewardsBase:        0,
		}
		b := a.WithUpdatedRewards(proto, 100)
		require.Equal(t, 100*a.MicroAlgos.RewardUnits(proto)-1, b.RewardedMicroAlgos.Raw)
	})
}

func makeString(len int) string {
	s := ""
	for i := 0; i < len; i++ {
		s += string(byte(i))
	}
	return s
}

func TestEncodedAccountDataSize(t *testing.T) {
	partitiontest.PartitionTest(t)

	oneTimeSecrets := crypto.GenerateOneTimeSignatureSecrets(0, 1)
	vrfSecrets := crypto.GenerateVRFSecrets()
	maxStateSchema := StateSchema{
		NumUint:      0x1234123412341234,
		NumByteSlice: 0x1234123412341234,
	}
	ad := AccountData{
		Status:             NotParticipating,
		MicroAlgos:         MicroAlgos{},
		RewardsBase:        0x1234123412341234,
		RewardedMicroAlgos: MicroAlgos{},
		VoteID:             oneTimeSecrets.OneTimeSignatureVerifier,
		SelectionID:        vrfSecrets.PK,
		VoteFirstValid:     Round(0x1234123412341234),
		VoteLastValid:      Round(0x1234123412341234),
		VoteKeyDilution:    0x1234123412341234,
		AssetParams:        make(map[AssetIndex]AssetParams),
		Assets:             make(map[AssetIndex]AssetHolding),
		AppLocalStates:     make(map[AppIndex]AppLocalState),
		AppParams:          make(map[AppIndex]AppParams),
		TotalAppSchema:     maxStateSchema,
		AuthAddr:           Address(crypto.Hash([]byte{1, 2, 3, 4})),
	}

	// TODO after applications enabled: change back to protocol.ConsensusCurrentVersion
	currentConsensusParams := config.Consensus[protocol.ConsensusFuture]

	for assetCreatorAssets := 0; assetCreatorAssets < currentConsensusParams.MaxAssetsPerAccount; assetCreatorAssets++ {
		ap := AssetParams{
			Total:         0x1234123412341234,
			Decimals:      0x12341234,
			DefaultFrozen: true,
			UnitName:      makeString(currentConsensusParams.MaxAssetUnitNameBytes),
			AssetName:     makeString(currentConsensusParams.MaxAssetNameBytes),
			URL:           makeString(currentConsensusParams.MaxAssetURLBytes),
			Manager:       Address(crypto.Hash([]byte{1, byte(assetCreatorAssets)})),
			Reserve:       Address(crypto.Hash([]byte{2, byte(assetCreatorAssets)})),
			Freeze:        Address(crypto.Hash([]byte{3, byte(assetCreatorAssets)})),
			Clawback:      Address(crypto.Hash([]byte{4, byte(assetCreatorAssets)})),
		}
		copy(ap.MetadataHash[:], makeString(32))
		ad.AssetParams[AssetIndex(0x1234123412341234-assetCreatorAssets)] = ap
	}

	for assetHolderAssets := 0; assetHolderAssets < currentConsensusParams.MaxAssetsPerAccount; assetHolderAssets++ {
		ah := AssetHolding{
			Amount: 0x1234123412341234,
			Frozen: true,
		}
		ad.Assets[AssetIndex(0x1234123412341234-assetHolderAssets)] = ah
	}

	maxProg := []byte(makeString(config.MaxAvailableAppProgramLen))
	maxGlobalState := make(TealKeyValue, currentConsensusParams.MaxGlobalSchemaEntries)
	maxLocalState := make(TealKeyValue, currentConsensusParams.MaxLocalSchemaEntries)

	for globalKey := uint64(0); globalKey < currentConsensusParams.MaxGlobalSchemaEntries; globalKey++ {
		prefix := fmt.Sprintf("%d|", globalKey)
		padding := makeString(currentConsensusParams.MaxAppKeyLen - len(prefix))
		maxKey := prefix + padding
		maxValue := TealValue{
			Type:  TealBytesType,
			Bytes: makeString(currentConsensusParams.MaxAppSumKeyValueLens - len(maxKey)),
		}
		maxGlobalState[maxKey] = maxValue
	}

	for localKey := uint64(0); localKey < currentConsensusParams.MaxLocalSchemaEntries; localKey++ {
		prefix := fmt.Sprintf("%d|", localKey)
		padding := makeString(currentConsensusParams.MaxAppKeyLen - len(prefix))
		maxKey := prefix + padding
		maxValue := TealValue{
			Type:  TealBytesType,
			Bytes: makeString(currentConsensusParams.MaxAppSumKeyValueLens - len(maxKey)),
		}
		maxLocalState[maxKey] = maxValue
	}

	for appCreatorApps := 0; appCreatorApps < currentConsensusParams.MaxAppsCreated; appCreatorApps++ {
		ap := AppParams{
			ApprovalProgram:   maxProg,
			ClearStateProgram: maxProg,
			GlobalState:       maxGlobalState,
			StateSchemas: StateSchemas{
				LocalStateSchema:  maxStateSchema,
				GlobalStateSchema: maxStateSchema,
			},
		}
		ad.AppParams[AppIndex(0x1234123412341234-appCreatorApps)] = ap
	}

	for appHolderApps := 0; appHolderApps < currentConsensusParams.MaxAppsOptedIn; appHolderApps++ {
		ls := AppLocalState{
			KeyValue: maxLocalState,
			Schema:   maxStateSchema,
		}
		ad.AppLocalStates[AppIndex(0x1234123412341234-appHolderApps)] = ls
	}

	encoded := ad.MarshalMsg(nil)
	require.GreaterOrEqual(t, MaxEncodedAccountDataSize, len(encoded))
}

func TestEncodedAccountAllocationBounds(t *testing.T) {
	partitiontest.PartitionTest(t)

	// ensure that all the supported protocols have value limits less or
	// equal to their corresponding codec allocbounds
	for protoVer, proto := range config.Consensus {
		if proto.MaxAssetsPerAccount > encodedMaxAssetsPerAccount {
			require.Failf(t, "proto.MaxAssetsPerAccount > encodedMaxAssetsPerAccount", "protocol version = %s", protoVer)
		}
		if proto.MaxAppsCreated > EncodedMaxAppParams {
			require.Failf(t, "proto.MaxAppsCreated > encodedMaxAppParams", "protocol version = %s", protoVer)
		}
		if proto.MaxAppsOptedIn > EncodedMaxAppLocalStates {
			require.Failf(t, "proto.MaxAppsOptedIn > encodedMaxAppLocalStates", "protocol version = %s", protoVer)
		}
		if proto.MaxLocalSchemaEntries > EncodedMaxKeyValueEntries {
			require.Failf(t, "proto.MaxLocalSchemaEntries > encodedMaxKeyValueEntries", "protocol version = %s", protoVer)
		}
		if proto.MaxGlobalSchemaEntries > EncodedMaxKeyValueEntries {
			require.Failf(t, "proto.MaxGlobalSchemaEntries > encodedMaxKeyValueEntries", "protocol version = %s", protoVer)
		}
	}
}

func TestAppIndexHashing(t *testing.T) {
	partitiontest.PartitionTest(t)

	i := AppIndex(12)
	prefix, buf := i.ToBeHashed()
	require.Equal(t, protocol.HashID("appID"), prefix)
	require.Equal(t, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c}, buf)

	i = AppIndex(12 << 16)
	prefix, buf = i.ToBeHashed()
	require.Equal(t, protocol.HashID("appID"), prefix)
	require.Equal(t, []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00}, buf)

	// test value created with:
	// python -c "import algosdk.encoding as e; print(e.encode_address(e.checksum(b'appID'+($APPID).to_bytes(8, 'big'))))"
	i = AppIndex(77)
	require.Equal(t, "PCYUFPA2ZTOYWTP43MX2MOX2OWAIAXUDNC2WFCXAGMRUZ3DYD6BWFDL5YM", i.Address().String())
}